【问题标题】:Linking C++ static Library in C using gcc使用 gcc 在 C 中链接 C++ 静态库
【发布时间】:2014-07-01 10:49:08
【问题描述】:

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

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

【问题讨论】:

  • 您可以使用gcc -x c++指定输入语言
  • 与您的直接问题无关,但您应该在testcplusplus.c 中包含testcplusplus.h(可能应该有扩展名.cc.cpp,以确保它被识别为C++文件)。
  • 另外:如果可执行文件中有任何 C++,main 应该是 C++。 (虽然我不知道现代实现是否仍然需要这个。)
  • 你仍然需要链接 C++ 运行时,至少,肯定的。

标签: c++ c gcc g++


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 我使用了您的建议,先生,但仍然遇到一些错误。我必须使用 -lstdc++ 选项和 gcc 才能成功编译 test.c
  • 好的,这是另一个方面:可执行文件需要链接到标准 C++ 库,否则您将获得未定义的引用。我会将其添加到答案中。
【解决方案2】:

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

而是将它们包含在testcplusplus.c中,这样C编译器就只能看到C++代码的C兼容接口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 2017-01-31
    • 2010-10-23
    相关资源
    最近更新 更多