简体   繁体   English

将 C 与 C++ 联系起来

[英]Linking C with C++

I have a open source C project and if I try to execute examples it is working fine but if i try to call those functions from C++ by using extern (including all headers with function definition) it is throwing error undefined reference to function_name.我有一个开源 C 项目,如果我尝试执行示例,它工作正常,但是如果我尝试使用 extern(包括所有带有函数定义的头文件)从 C++ 调用这些函数,则会抛出错误 undefined reference to function_name。 Can someone help me out how to properly wrap the C code using C++ and calling functions directly from C++ by just including headers of C?有人可以帮助我解决如何使用 C++ 正确包装 C 代码并通过仅包含 C 的头文件直接从 C++ 调用函数吗?

You need extern "C" language linkage to declare C functions in your C++ code.您需要extern "C"语言链接才能在 C++ 代码中声明 C 函数。

This (among other things) prevents the name mangling otherwise used by the C++ compiler for functions.这(除其他外)可以防止 C++ 编译器对函数使用的名称修改

Commonly extern "C" is added using conditional compilation in header files by checking the existence of the __cplusplus macro:通常通过检查__cplusplus宏的存在,在头文件中使用条件编译添加extern "C"

#ifdef __cplusplus
extern "C" {
#endif

// Function declarations

#ifdef __cplusplus
} // End of the extern "C" block
#endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM