简体   繁体   English

使用autotools从C ++使用C代码

[英]Using C code from C++ using autotools

I am writing a (my first) C++ class on top of some code written in C, but I can only get the C++ to compile by declaring the C functions in a extern block. 我正在用C编写的一些代码编写一个(我的第一个)C ++类,但是我只能通过在extern块中声明C函数来编译C ++。 My project uses autotools; 我的项目使用autotools; is there any way to automate this process so I don't have to maintain two header files? 有没有办法自动化这个过程,所以我不必维护两个头文件?

Use a extern block inside a #ifdef in C codes header files 在C代码头文件中的#ifdef中使用extern块

Start of header files 头文件的开头

#ifdef __cplusplus
extern "C" {
#endif

...and at end of the header files ...并在头文件的末尾

#ifdef __cplusplus
}
#endif

This way it will work for being included in both C and C++ sources 这样它就可以包含在C和C ++源代码中

Yes create wrapper header files which include your C header files like so... 是创建包装头文件,其中包括您的C头文件,如此...

//Wrapper.h
#ifdef __cplusplus
extern "C"
{

    #include "Actual.h"
}
#else
    #include "Actual.h"
#endif


//Use.cpp
#include "Wrapper.h"

int main()
{
    return 0;
}

//Use.c
#include "Wrapper.h"
/*or #include "Actual.h" */

int main()
{
    return 0;
}

Use the C Preprocessor. 使用C预处理器。 Do something like this: 做这样的事情:

 #ifdef __cplusplus
 extern "C" {
 #endif 
// code goes here

#ifdef __cplusplus
}
#endif

We have a macro in a header file: 我们在头文件中有一个宏:

#ifdef __cplusplus
    #define _crtn "C"
#else
    #define _crtn
#endif

Then in header files, we can use _crtn : 然后在头文件中,我们可以使用_crtn

#include "croutine.h"

extern _crtn void MyFunction( ... );

The only gotcha is to make sure you include the header file containing the prototype of MyFunction inside the file containing the implementation of MyFunction so that it is compiled with "C" linkage. 唯一的问题是确保在包含MyFunction实现的文件中包含包含MyFunction原型的头文件,以便使用“C”链接进行编译。

This is the same as @epatel's answer, but only requires the ugly #ifdef 's in one header file. 这与@ epatel的答案相同,但只需要在一个头文件中使用丑陋的#ifdef

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

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