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++
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With