Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect a C program to a C++ library without needing stdc++ to link them?

Tags:

c++

c

linker

I am trying to add some code to a larger C project that requires the use of a C++ library.

The C++ library provides a wrapper using functions marked extern "C" that provide access to the functionality of the library

//Some C++ library
//mywrapper.h
#ifdef __cplusplus
extern "C" {
#endif

void wrapperFunction1( int width );
void wrapperFunction1( int height);
#ifdef __cplusplus
} // extern "C"
#endif

This compiles with g++ without problem.

When making a C program and including mywrapper.h, I continually get linker errors referencing vtable and cxa_pure_virtual:

undefined reference to `vtable for __cxxabiv1::__class_type_info'
undefined reference to `__cxa_pure_virtual'

In testing, these errors go away and allow the program to compile when I add the stdc++ library, but this isn't a option for the larger C project. Is there a way to compile a C program to access a C++ library without these errors and without stdc++? And the deals of the errors are referring to modules that are deep inside of the C++ library and not referenced in mywrapper.h, so why is C program even trying to refer to them?

like image 253
Michael Curran Avatar asked Nov 22 '25 10:11

Michael Curran


2 Answers

A C++ library depends on standard C++ library (libstdc++, -lstdc++ option to linker, defaulted if you run linker via g++). That's a fact. Nothing can be done about it. Get over it.

The wrapper header does not refer to those symbols, but the actual object files in the library do. So they need to be defined and the way to define them is to include the standard C++ library.

Note, that if the wrapped library itself is dynamic, it will know it's dependencies and you won't have to specify linking against libstdc++ dynamically.

like image 123
Jan Hudec Avatar answered Nov 24 '25 00:11

Jan Hudec


It is the C++ library you've wrapped that requires stdc++, not your wrapper.

You've wrapped the C++ functions so that they are callable from C but they still use a library internally that depends on the C++ standard library. If you don't provide stdc++, the library you're using is missing part of its implementation. Unless you rewrite the C++ library, there is no way round that.

like image 35
thehouse Avatar answered Nov 24 '25 01:11

thehouse