8

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

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
Cartesius00
  • 23,584
  • 43
  • 124
  • 195
  • What is the name of the static library file? is it of the form "lib.a"? if it is you should be able to use the compiler flags "-L -l" – Node Sep 02 '11 at 19:37
  • I get: ./liba.a(liba.o):(.eh_frame+0x12): undefined reference to `__gxx_personality_v0' collect2: ld returned 1 exit status – Cartesius00 Sep 02 '11 at 19:39

3 Answers3

9

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.

chmeee
  • 3,608
  • 1
  • 21
  • 28
  • Good point. But ping() just returns number 1, and still need to compile main project with g++. Is it OK? – Cartesius00 Sep 02 '11 at 19:44
  • Given the error you pasted above, you do need to link using g++. You can compile some files with gcc, but g++ needs to be used as the linker (That or explicitly add -lstdc++ to your LDFLAGS/linker command line). – chmeee Sep 02 '11 at 19:45
  • 1
    One question: If I need to call a DLL (compiled with g++) from C (compiled with gcc) is it possible then? (instead of static linking) – Cartesius00 Sep 02 '11 at 20:12
  • 1
    Yep, as long as you either a) handle name mangling yourself, or b) mark the symbols as `extern "C"`. – chmeee Sep 02 '11 at 20:25
2

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?

Community
  • 1
  • 1
1

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

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138