我正在做一个有很多遗留C代码的项目。我们已经开始用c++编写,目的是最终转换遗留代码。我对C和c++如何交互有点困惑。我知道,通过用extern“C”包装C代码,c++编译器不会损坏C代码的名称,但我不完全确定如何实现这一点。
因此,在每个C头文件的顶部(在include守卫之后),我们有
#ifdef __cplusplus
extern "C" {
#endif
在底部,我们写上
#ifdef __cplusplus
}
#endif
在这两者之间,我们有所有的include、typedef和函数原型。我有几个问题,看看我是否理解正确:
If I have a C++ file A.hh which includes a C header file B.h, includes another C header file C.h, how does this work? I think that when the compiler steps into B.h, __cplusplus will be defined, so it will wrap the code with extern "C" (and __cplusplus will not be defined inside this block). So, when it steps into C.h, __cplusplus will not be defined and the code will not be wrapped in extern "C". Is this correct? Is there anything wrong with wrapping a piece of code with extern "C" { extern "C" { .. } }? What will the second extern "C" do? We don't put this wrapper around the .c files, just the .h files. So, what happens if a function doesn't have a prototype? Does the compiler think that it's a C++ function? We are also using some third-party code which is written in C, and does not have this sort of wrapper around it. Any time I include a header from that library, I've been putting an extern "C" around the #include. Is this the right way to deal with that? Finally, is this set up a good idea? Is there anything else we should do? We're going to be mixing C and C++ for the foreseeable future, and I want to make sure we're covering all our bases.