Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ shared library called from C

I have a shared library written in C++. It exports a visible interface made of extern "C" functions which create, destroy and manipulate opaque types.

Now, I'd like to have a pure C program which uses this library.

Can I do this (platform independently) ? When will the C++ runtime and the C++ static objects get initialized if main is not written in C++ ?

like image 476
Alexandre C. Avatar asked Dec 23 '11 14:12

Alexandre C.


People also ask

What is a shared library in C?

Shared libraries (also called dynamic libraries) are linked into the program in two stages. First, during compile time, the linker verifies that all the symbols (again, functions, variables and the like) required by the program, are either linked into the program, or in one of its shared libraries.

How are library files called in C?

A library in C is a collection of header files, exposed for use by other programs. The library therefore consists of an interface expressed in a . h file (named the "header") and an implementation expressed in a . c file.

How do you call a function in a shared library?

Dynamically calling a function from a shared library can only be accomplished in Go using 'cgo' and, even then, the function pointer returned by 'dlsym' can only be called via a C bridging function as calling C function pointers directly from Go is not currently supported.

What is the difference between C executable and C library?

A library is exactly like an executable, except instead of running directly, the library functions are invoked with parameters from your executable. You would be familiar about the compilation of a C file.


1 Answers

The initialization phase is platform dependent. In the case of Linux, dynamically loaded libraries can have specially declared symbols that are automatically called by dlopen() when the library is loaded.

See the manpage for dlopen(3), section The obsolete symbols init() and fini() for more info.

Static initializers are implicitly marked as __attribute__((constructor)), so in general you don't have to do anything special to have them called when the shared library is loaded. I suspect this is the same or similar on other platforms.

like image 161
onitake Avatar answered Oct 01 '22 23:10

onitake