How to use C code in C++

自古美人都是妖i 提交于 2019-12-03 02:42:47

问题


Just a small question: Can C++ use C header files in a program?

This might be a weird question, basically I need to use the source code from other program (made in C language) in a C++ one. Is there any difference between both header files in general? Maybe if I change some libraries... I hope you can help me.


回答1:


Yes, you can include C headers in C++ code. It's normal to add this:

#ifdef __cplusplus
extern "C"
{
#endif

// C header here

#ifdef __cplusplus
}
#endif

so that the C++ compiler knows that function declarations etc. should be treated as C and not C++.




回答2:


If you are compiling the C code together, as part of your project, with your C++ code, you should just need to include the header files as per usual, and use the C++ compiler mode to compile the code - however, some C code won't compile "cleanly" with a C++ compiler (e.g. use of malloc will need casting).

If on, the other hand, you have a library or some other code that isn't part of your project, then you do need to make sure the headers are marked as extern "C", otherwise C++ naming convention for the compiled names of functions will apply, which won't match the naming convention used by the C compiler.

There are two options here, either you edit the header file itself, adding

#ifdef __cplusplus 
extern "C" {
#endif

... original content of headerfile goes here. 

#ifdef __cplusplus 
}
#endif

Or, if you haven't got the possibility to edit those headers, you can use this form:

#ifdef __cplusplus 
extern "C" {
#endif
#include <c_header.h>
#ifdef __cplusplus 
}
#endif



回答3:


Yes, but you need to tell the C++ compiler that the declarations from the header are C:

extern "C" {
#include "c-header.h"
}

Many C headers have these included already, wrapped in #if defined __cplusplus. That is arguably a bit weird (C++ syntax in a C header) but it's often done for convenience.



来源:https://stackoverflow.com/questions/17448014/how-to-use-c-code-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!