我有一个用 C++ 编写的外部库,例如
外部.h
#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H
#include <cstdint>
extern "C" uint8_t myCppFunction(uint8_t n);
#endif
外部.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 文件使用它。
我的问题是:
- 有没有办法可以在我的 C 项目中使用这个 C++ 库,而无需修改我的库?
- 如果不是,我需要在图书馆方面做什么才能使其成为可能?
最佳答案
c
cstdint
中的前缀因为它实际上是从C合并而来的头文件,C中的名字是stdint.h
.
您需要通过检测 __cplusplus
有条件地包含正确的 header 宏。您还需要此宏才能使用 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
关于c++ - 从 C 文件调用 C++ 标准头 (cstdint),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72182138/