0

I am trying to execute basic code in C and C++ in Linux environment. I am using eclipse to run it. Current project is created as C project.

All I am trying to do is to call a function from different file in same folder. I have my main in sample.c, In main I would like to call function sum(int a, int b) in A.c. I was able to run it. But when I rewrite same function sum in A.cpp(a C++ template file) it throws linker error.

gcc  -o "Test"  ./sample.o 

./sample.o: In function main':/home/idtech/workspace/Test/Debug/../sample.c:19: undefined reference to sum' collect2: ld returned 1 exit status make: * [Test] Error 1

I need help in calling functions in C++ file from C file in same folder. Please help me to solve this linker issue.

Thanks

Harsha

4

1 に答える 1

2

C++ コンパイラは、型情報をエンコードするためにシンボル名をマングルします。通常、C コードに公開する必要がある C++ 関数を作成するときは、次のextern "C" { ... }ように関数をブロックでラップする必要があります (またはextern "C"、@DaoWen が指摘したようにプレフィックスを付けます)。

A.cpp:

extern "C" {
    int sum(int a, int b)
    {
        return a+b;
    }
}

caller.c:

extern int sum(int a, int b);
...
int main() { sum(42, 4711); }

関数を としてマークすることによりextern "C"、それをオーバーロードする機能が犠牲になります。さまざまなオーバーロードは、マングルされたシンボル名によってのみ区別できるためです。これが意味することは、これを行うことができないということです:

extern "C" {
    int sum(int a, int b) { return a+b; }
    float sum(float a, float b) { return a+b; } // conflict!
}
于 2013-07-12T17:04:58.303 に答える