16

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

jules
  • 1,897
  • 2
  • 16
  • 19

2 Answers2

8

It works just as expected. Make sure you haven't accidentally compiled sample1.c with g++.

chill
  • 16,470
  • 2
  • 40
  • 44
  • 2
    And there's an easy way to find out, run `nm sample1.o`, there should be 1 non-mangled symbol for `add` , if there isn't, then something else than `gcc -c sample1.c` generated the sample1.o file. – nos Nov 20 '12 at 16:49
  • 2
    Thank you very much, that was the problem! I compiled both files with g++ – jules Nov 20 '12 at 16:51
3

It works on my machine. Try GCC 4.7.0

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66