Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including C Code in C++

Tags:

c++

c

g++

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

like image 378
jules Avatar asked Nov 20 '12 16:11

jules


1 Answers

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

like image 158
chill Avatar answered Nov 15 '22 11:11

chill