如何在 C++ 中使用 C 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17448014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use C code in C++
提问by SadSeven
Just a small question: Can C++ use C header files in a program?
只是一个小问题:C++ 可以在程序中使用 C 头文件吗?
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.
这可能是一个奇怪的问题,基本上我需要在 C++ 程序中使用其他程序(用 C 语言编写)的源代码。一般来说,这两个头文件之间有什么区别吗?也许如果我改变一些图书馆......我希望你能帮助我。
回答by RichieHindle
Yes, you can include C headers in C++ code. It's normal to add this:
是的,您可以在 C++ 代码中包含 C 头文件。添加这个是正常的:
#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++.
以便 C++ 编译器知道函数声明等应该被视为 C 而不是 C++。
回答by Mats Petersson
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).
如果您将 C 代码作为项目的一部分与 C++ 代码一起编译,则只需要像往常一样包含头文件,并使用 C++ 编译器模式编译代码 - 但是,一些 C 代码获胜不使用 C++ 编译器“干净地”编译(例如,使用malloc
will 需要强制转换)。
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.
另一方面,如果您有一个库或其他一些不属于您的项目的代码,那么您需要确保将标头标记为extern "C"
,否则将应用 C++ 编译函数名称的命名约定,这与 C 编译器使用的命名约定不匹配。
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
回答by unwind
Yes, but you need to tell the C++ compiler that the declarations from the header are C:
是的,但是您需要告诉 C++ 编译器头文件中的声明是 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.
许多 C 头文件已经包含这些,包裹在#if defined __cplusplus
. 这可能有点奇怪(C 头文件中的 C++ 语法),但通常是为了方便起见。