简体   繁体   中英

Linking C++ to C in GCC

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

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.

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?

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++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM