在C ++中包含C代码
我试图将C代码包含在一个简单的C ++程序中,但我遇到了一个意想不到的问题 – 当我尝试编译程序时,g ++会出现以下错误:
/tmp/cccYLHsB.o: In function `main': test1.cpp:(.text+0x11): undefined reference to `add'
我搜索了一个解决方案并找到了本教程:
http://www.parashift.com/c++-faq/overview-mixing-langs.html
我的程序似乎没什么区别所以我有点迷失了……
我的C ++程序如下所示:
test1.ccp
#include using namespace std; extern "C" { #include "sample1.h" } int main(void) { int x= add(3); cout << "the current value of x is " << x << endl; return 0; }
sample1标头和函数如下所示:
sample1.h
#include double add(const double a);
sample1.c
#include "sample1.h" double add(const double a) { printf("Hello World\n"); return a + a; }
对于编译,我首先使用g ++编译test1.o,使用gcc编译sample1.o(尝试g ++也没有区别)
g++ -c test1.cpp gcc -c sample1.c
这按预期工作。 之后我尝试链接这个程序:
g++ sample1.o test1.o -o test
这是我得到上述错误的地方
test1.cpp:(.text+0x11): undefined reference to `add'
我觉得我错过了一些重要但却看不到的东西。
任何帮助都非常感谢!
问候
儒勒
它的工作方式与预期一致。 确保你没有用g++
意外编译sample1.c
。
它适用于我的机器。 试试GCC 4.7.0