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

塞缪尔

在下面的代码中,我试图从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;
}

测试

#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
有害的

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

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

在更大的示例中,将testcplusplus.h拆分为两个标头可能是适当的:一个标头仅包含要提供给C环境的外部接口的声明,另一个标头包含其余的-C ++实现内部所需的声明以及任何所需的声明包括在内。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章