Binding C ++ to C in GCC

I have one extern "C" int ping(void) function 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 am using g++ / gcc , but I cannot link the C executable to the C++ shared library. Please, how can this be done? Could you provide the exact gcc commands?

Edit

 g++ -c -static liba.cpp ar rcs liba.a liba.o gcc -ox 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

+7
source share
3 answers

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

+10
source

Take a look at mangling. If the C ++ library does not export the names "extern C", it becomes interesting in one of three ways, depending on which compiler was used to build the library.

Even then you will not get satisfactory results, since many C ++ concepts will not be handled properly by a program that starts on the C side of the fence. You do not think that a program actually makes any of the indirectly called static C ++ blocks when it does not understand the guarantees of such a β€œforeign” language, right?

Short version of the story. Even if you program in C, if you want to properly handle the C ++ library, you need your main C ++ compilation.

+1
source

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

See also:

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

What is the difference between g ++ and gcc?

+1
source

All Articles