使用gcc在C中链接C ++静态库

时间:2014-07-01 10:49:09

标签: c++ c gcc g++

在下面的代码中,我试图用C函数调用用C ++编写的虚函数(使用像ap_fixed.h,ap_int.h这样的C ++头文件)。我用g ++编译时代码运行正常。但是当我使用gcc编译test.c时,它会抛出一个错误,因为我已经包含了一个有效错误的C ++头文件。

是否有使用gcc编译的解决方法?我从一些帖子中读到,以这种方式合并C / C ++代码并不是一个好习惯。如果对使用大型C代码库和做类似的事情有任何严重的反响,请告诉我。

由于

头文件:testcplusplus.h

#include "ap_fixed.h"
#include "ap_int.h"

#ifdef __cplusplus
extern "C" {
#endif

void print_cplusplus();

#ifdef __cplusplus
}
#endif

testcplusplus.cc

#include <iostream>
#include "testcplusplus.h"

void print_cplusplus() {

ap_ufixed<10, 5,AP_RND_INF,AP_SAT > Var1 = 22.96875; 
std::cout << Var1 << std::endl;
}

test.c的

#include <stdio.h>
#include "testcplusplus.h"

int main() {
print_cplusplus();
}

使用的命令:

g++ -c -o testcplusplus.o testcplusplus.cc 
ar rvs libtest.a testcplusplus.o
gcc -o test test.c -L. -ltest

错误:

In file included from ap_fixed.h:21:0,
                 from testcplusplus.h:1,
                 from test.c:2:
ap_int.h:21:2: error: #error C++ is required to include this header file

2 个答案:

答案 0 :(得分:3)

这里的问题是C ++头文件ap_fixed.h包含在C程序test.c中(间接通过testcplusplus.h)。

解决方案是删除标题的包含&#34; ap_fixed.h&#34; 和&#34; ap_int.h&#34;来自testcplusplus.h并直接从testcplusplus.cpp中包含它们。 C程序无论如何都不需要知道这些,只有C ++包装器直接使用它们。

在一个更大的示例中,将testcplusplus.h拆分为两个标题可能是合适的:一个只包含您向C环境呈现的外部接口的声明,另一个包含其余内容 - C ++实现内部需要的声明以及任何必要的包括。

完成此操作后,您仍将面临链接错误,因为生成的可执行文件将包含对C ++运行时库中的符号的引用,以及C ++代码使用的任何其他库。要解决此问题,请在编译最终可执行文件时添加-l指令,例如:

gcc -o test test.c -L. -ltest -lstdc++

答案 1 :(得分:1)

此时您不需要包含 ap_int.h ap_fixed.h ,因为print_cplusplus函数的声明不需要这些定义

相反,将它们包含在 testcplusplus.c 中,因此C编译器只能看到C ++代码的C兼容接口。

相关问题