在C ++中包含C代码 [英] Including C Code in C++
问题描述
/tmp/cccYLHsB.o:在函数main中:
test1.cpp :(。text + 0x11):未定义的引用
我搜索了一个解决方案,发现本教程:
a href =http://www.parashift.com/c++-faq/overview-mixing-langs.html> http://www.parashift.com/c++-faq/overview-mixing-langs.html a>
似乎对我的程序没有区别,所以我有点失落...
我的C ++程序如下所示:
test1.ccp
#include< iostream>
using namespace std;
externC{
#includesample1.h
}
int main(void)
{
int x = add(3);
cout<< x的当前值是< x < endl;
return 0;
}
sample1标题和函数如下所示:
sample1.h
#include< stdio.h>
double add(const double a);
sample1.c
#includesample1.h
double add(const double a)
{
printf(Hello World\\\
);
return a + a;
}
对于编译,我首先使用g ++和sample1.o编译test1.o gcc(尝试g ++也没有差别)
g ++ -c test1.cpp
gcc - c sample1.c
这样工作正常。然后我尝试这样链接程序:
g ++ sample1.o test1.o -o test
这是我收到上述错误的地方
test1.cpp :(。text + 0x11):未定义引用`add'
<
任何帮助都非常感谢!
尊敬
jules
解决方案工作正如预期。请确保您没有不小心使用 g ++
编译了 sample1.c
。
I'm trying to include C code into a simple C++ program but I ran into an unexpected problem - when I try to compile the program g++ gives the following error:
/tmp/cccYLHsB.o: In function `main':
test1.cpp:(.text+0x11): undefined reference to `add'
I searched for a solution and found this tutorial:
http://www.parashift.com/c++-faq/overview-mixing-langs.html
There seems to be no difference to my program so I'm a bit lost...
My C++ program looks like this:
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;
}
The sample1 header and function look like this:
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;
}
For compilation I first compile a test1.o with g++ and sample1.o with gcc (tried g++ also but makes no difference)
g++ -c test1.cpp
gcc -c sample1.c
That works as expected. Afterwards I try to link the program like this:
g++ sample1.o test1.o -o test
This is where I get the error mentioned above
test1.cpp:(.text+0x11): undefined reference to `add'
I have the feeling that I'm missing something important but just can't see it.
Any help is highly appreciated!
Regards
jules
解决方案 It works just as expected. Make sure you haven't accidentally compiled sample1.c
with g++
.
这篇关于在C ++中包含C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!