【发布时间】: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++ 运行时,至少,肯定的。