![](/img/trans.png)
[英]How can I build a C/C++ program using `static linking` & `Dynamic linking` with gcc & Visual studio?
[英]Linking C++ static Library in C using gcc
在下面的代码中,我试图从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++
此时您不需要包括ap_int.h和ap_fixed.h ,因为print_cplusplus
函数的声明不需要这些定义。
而是将它们包含在testcplusplus.c中 ,因此C编译器只能看到C ++代码的C兼容接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.