Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I link a mixed C/C++ static library that has a C interface using gcc?

Tags:

c++

c

gcc

g++

I have a mixed C/C++ library.

On the outside it provides a C interface using extern C. Internally there are templates and classes. Creating the library with "ar" posed no problems. The file is called libo-client.a.

However, when linking the .a file using gcc (not g++) I get lots of errors that look like this:

libo-client.a(mysocket.o):(.rodata._ZTV7mStream[vtable for mStream]+0x10): undefined reference to `__cxa_pure_virtual'
...
mysocket.cpp:(.text+0x15ad): undefined reference to `operator new[](unsigned long)'
mysocket.cpp:(.text+0x15c1): undefined reference to `operator delete(void*)'
mysocket.cpp:(.text+0x167a): undefined reference to `__cxa_allocate_exception'
mysocket.cpp:(.text+0x16a6): undefined reference to `__cxa_throw'
...

My compile/link line looks like this:

gcc $(CFLAGS) $(INCLUDES) test2.c libo-client.a -o test2 

Where test2 is my test harness.

This problem does not occur when I'm using g++. However, I'm going to interface this library into C project which is compiled with gcc. How do I get around this? What's the cause of it?

EDIT:

Even though I'm not using the standard C++ library it's obviously needing some things like operator new/delete etc. and there are exceptions internally.

I'm linking this thing against the Xen hypervisor so I'm not sure what options i have but to totally rewrite this thing or perhaps try compiling Xen with G++ instead?

like image 263
hookenz Avatar asked Dec 09 '22 06:12

hookenz


1 Answers

The simplest way around your problem it is to link with g++; this gets the correct libraries in place.

The problem is that C++ has a lot of requirements that C does not, and does more work before calling main() to ensure that things are properly initialized.

If you insist on linking with the C compiler, at the very least you'd have to include the C++ support library in with your link command.

like image 59
Jonathan Leffler Avatar answered May 08 '23 05:05

Jonathan Leffler