Yet another C/C++ integration question: I am trying to update some legacy C library (let's call it libcl.a
) with functionality that I have in a C++ library (let's call it libcppl.a
). The liblc.a
library is being used all over in my environment and is linked into many C projects, using GCC (in the C compiler mode):
>> gcc prog.c -lcl
The libcl.a
currently consists of the cl.o
object file (created with gcc
from cl.c
+cl.h
).
The libcppl.a
consists of the cppl.o
object file (created with g++
from cppl.cpp
+cppl.h
).
Because the existing applications are written in C, and the build scripts are using GCC, I'd like to keep the transition to the updated library as simple as possible. Thus, I want to keep using GCC as the main compiler but still be able to link with the updated library.
Finding this answer, I could link C++ objects into GCC C project using -lstdc++
:
>> gcc -c cl.c -o cl.o
>> g++ -c cppl.c -o cppl.o
>> ar rcs libcl.a cl.o cppl.o
>> gcc prog.c -lcl -lstdc++
However, I want to eliminate the explicit mention of the libstdc++
in the compile command line.
What I tried to do was to include libstdc++ in the cl library, by doing:
>> ar rcs libcl.a cl.o cppl.o /usr/lib/libstdc++.so.6
However, when building the application, I get:
>> gcc prog.c -lcl
In file included from cppl.cpp:2:
./libcl.a(cppl.o):(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
1. Why doesn't the gcc linker find the C++ standard library that was archived together with my objects?
2. Is there a limitation on using ar
with libraries (as opposed to object files)?
3. Is there a way to overcome this problem?
You can separately compile prog.c
using gcc
, then use g++
to link:
# compile the main program to an object file
gcc prog.c -o prog.o
#use g++ to link everything (it'll automatically pull in libstdc++)
g++ prog.o -lcl
Alternatively, you can compile and link prog.c
in one step by explicitly telling g++
to compile prog.c
as a C source file using the -x
option:
g++ -x c prog.c -lcl
See https://stackoverflow.com/a/5854712/12711 for more information on the difference in behavior between gcc
and g++
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With