gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:40 25 4
gpt4 key购买 nike

在下面的代码中,我试图从 C 函数调用一个用 C++ 编写的虚拟函数(使用 C++ 头文件,如 ap_fixed.h、ap_int.h)。当我用 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;
}

测试.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

最佳答案

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

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

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

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

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

关于c++ - 使用gcc在C中链接C++静态库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24508398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com