调用C++来自C文件的标准标头(CSTDINT)
我有一个用C ++编写的外部库,例如
external.h
#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H
#include <cstdint>
extern "C" uint8_t myCppFunction(uint8_t n);
#endif
external.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 ++库,而无需修改我的诽谤?
- 如果没有,我必须在图书馆一侧做什么才能使它成为可能?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
c
cstdint
中的前缀是因为它确实是来自C的标头文件。C中的名称是stdint.h
。您需要通过检测
__ cplusplus
宏来有条件地包含正确的标头。您还需要此宏才能使用extern“ c”
部分,因为这是c ++特定的:The
c
prefix incstdint
is because it's really a header file incorporated from C. The name in C isstdint.h
.You need to conditionally include the correct header by detecting the
__cplusplus
macro. You also need this macro to use theextern "C"
part, as that's C++ specific:您必须修改库。
用
&lt; cstdint&gt;
用&lt; stdint.h&gt;
。通常建议使用前者,但只有后者存在于C中。您还应该在
extern“ C”
上遇到错误。 下方放置以下内容来解决这一点通过在文件末尾的匹配部分
:然后可以从单个功能中删除
extern“ c”
。You have to modify the library.
Replace
<cstdint>
with<stdint.h>
. Normally the former is recommended, but only the latter exists in C.You should also be getting errors on
extern "C"
. That's solved by putting following right below the includes:With a matching section at the end of file:
Then
extern "C"
can be removed from individual functions.创建一个可与C携带的单独的标头,并在使用C编译器编译时使用该标头:
通过其他答案回答。用
#ifdef __cplusplus
保护C ++零件。请注意,(有些?全部?)编译器需要
main
函数,将使用C ++编译器编译,以供C ++和C正确工作。Create a separate header that is portable with C and use that header when compiling with C compiler:
Is answered by other answers. Protect the C++ parts with
#ifdef __cplusplus
.Note that (some? all?) compilers require the
main
function to be compiled with C++ compiler for C++ and C to work together properly. https://isocpp.org/wiki/faq/mixing-c-and-cpp#overview-mixing-langs如果您不想修改库标头,请创建一个新文件,例如
inculte_for_cpp/cstdint
withcontent 。之后,
#include&lt; cstdint&gt;
应该找到您的文件。If you don't want to modify the library header, create a new file, for example
includes_for_cpp/cstdint
with contentAdd the directory
includes_for_cpp
to the include path of your C project. After that,#include <cstdint>
should find your file.