我正在尝试将 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 <iostream>
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 header 和函数如下所示:
sample1.h
#include <stdio.h>
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
。
关于c++ - 在 C++ 中包含 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13477807/