我有一个用C++编写的外部库,如
external.h
#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H
#include <cstdint>
extern "C" uint8_t myCppFunction(uint8_t n);
#endifexternal.cpp
#include "external.h"
uint8_t myCppFunction(uint8_t n)
{
return n;
}目前,我别无选择,只能在我当前的C项目中使用这个C++库。但我的编译器告诉我
No such file or director #include <cstdint>在我的C项目中使用时
main.c
#include "external.h"
int main()
{
int a = myCppFunction(2000);
return a;
}我理解这是因为cstdint是我试图通过C文件使用的C++标准库。
我的问题是:
发布于 2022-05-10 07:24:31
c前缀在cstdint中是因为它实际上是一个来自C的头文件,C中的名称是stdint.h。
您需要通过检测__cplusplus宏有条件地包含正确的标头。您还需要这个宏来使用extern "C"部件,因为这是特定于C++的:
#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H
#ifdef __cplusplus
// Building with a C++ compiler
# include <cstdint>
extern "C" {
#else
// Building with a C compiler
# include <stdint.h>
#endif
uint8_t myCppFunction(uint8_t n);
#ifdef __cplusplus
} // Match extern "C"
#endif
#endif发布于 2022-05-10 07:24:35
你必须修改图书馆。
将<cstdint>替换为<stdint.h>。通常推荐前者,但在C中只有后者。
您还应该在extern "C"上得到错误。通过将以下内容放在包含项下面,可以解决这一问题:
#ifdef __cplusplus
extern "C" {
#endif在文件末尾有一个匹配的部分:
#ifdef __cplusplus
}
#endif然后可以从单个函数中删除extern "C"。
发布于 2022-05-10 07:27:40
,我是否可以在我的C项目中使用这个C++库而不修改我的libary?
创建一个与C一起移植的单独的标头,并在用C编译器编译时使用该标头:
// external_portable_with_c.h
// rewrite by hand or generate from original external.h
// could be just sed 's/cstdint/stdint.h/; s/extern "C"//'
#include <stdint.h>
uint8_t myCppFunction(uint8_t n);
// c_source_file.c
#include "external_portable_with_c.h"
void func() {
myCppFunction(1);
}如果不是,在图书馆方面我该怎么做才能做到呢?
被其他的答案所回答。用C++保护#ifdef __cplusplus部件。
注意到了(一些?全部?)编译器要求main函数与C++编译器一起编译,以便C++和C能够正确地协同工作。https://isocpp.org/wiki/faq/mixing-c-and-cpp#overview-mixing-langs
https://stackoverflow.com/questions/72182138
复制相似问题