Alexandre C.
Alexandre C.

Reputation: 56956

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

Upvotes: 11

Views: 792

Answers (3)

Puppy
Puppy

Reputation: 146930

Usually, shared library systems have an entry point of their own in which to do this work, not main but DLLs have a DLLMain where the implementation can put such code. However, in the general case, it is none of your business and it's the job of whatever compiler you used to deal with this issue.

Upvotes: 1

BЈовић
BЈовић

Reputation: 64223

Can I do this (platform independently) ?

The library loading is a platform dependent operation.

When will the C++ runtime and the C++ static objects get initialized if main is not written in C++ ?

Doesn't matter. They will be initialized before the main is entered.

Upvotes: 4

onitake
onitake

Reputation: 1409

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.

Upvotes: 5

Related Questions