Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking C++ to C in GCC

Tags:

c++

c

gcc

g++

linker

I have one function extern "C" int ping(void) in a C++ "static-library" project. Now, I would like to write a simple Hello-World C program that will call this function int x = ping();.

I use g++ / gcc but I cannot link the C executable with C++ shared library. Please, how can one do that? Could you please provide exact gcc commands?

Edit:

g++ -c -static liba.cpp
ar rcs liba.a liba.o
gcc -o x main.o -L. -la

and get:

./liba.a(liba.o):(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'

collect2: ld returned 1 exit status

like image 410
Cartesius00 Avatar asked Sep 02 '11 19:09

Cartesius00


3 Answers

You may have to use g++ as the linker, not gcc. If the ping() function uses any STL, or exceptions, new, etc, it probably links against libstdc++, which is automatically linked in when you use g++ as the linker.

like image 189
chmeee Avatar answered Sep 20 '22 23:09

chmeee


Look up name mangling. If the C++ library doesn't export "extern C" names, it gets interesting in one of three different ways, depending on which compiler was used to build the library.

Even then, you won't get satisfactory results, as a lot of C++ concepts won't be handled properly by a program that starts on the C side of the fence. You don't think that a C program is going to actually do any of the indirectly called C++ static blocks when it doesn't understand the guarantees of such a "foreign" language, do you?

The short version of the story. Even if you are programming in C, if you want to properly handle a C++ library, you need your main compiled in C++.

like image 20
Edwin Buck Avatar answered Sep 17 '22 23:09

Edwin Buck


I have good results in compiling and linking mixed C/C++ code with GCC, but you both need the "extern C" (explicitly declaring functions as C functions) and linking against the C++ libraries with -lstdc++.

See also:

In C++ source, what is the effect of extern "C"?

What is the difference between g++ and gcc?

like image 22
Ingemar Ragnemalm Avatar answered Sep 21 '22 23:09

Ingemar Ragnemalm