Including C Code in C++

ぃ、小莉子 提交于 2019-12-21 03:45: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


回答1:


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




回答2:


It works on my machine. Try GCC 4.7.0



来源:https://stackoverflow.com/questions/13477807/including-c-code-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!