igor.sol
igor.sol

Reputation: 647

How to make C function dynamically exported

My application works with static library which has extensions API. The API is able to call extension init function from the external shared library or from the "local" binary. That is I can include extension init function statically in to the main executable binary.

The local function is searched by dlsym call and init function should be dynamically exported from the main binary. That is following nm call:

nm -CD <binary>

should list my init function.

Let's assume init function has this signature:

int init_func(INIT_STRUCT *);

This function is not called directly - it is only supposed to be loaded by dlsym call.

So I have two related question:

  1. how to force linker to not exclude this function from the generated binary?
  2. how to force compiler/linker to export this function dynamically?

(I use gcc to compile and link my program)

Upvotes: 0

Views: 1765

Answers (2)

igor.sol
igor.sol

Reputation: 647

Ok, I will post an answer based on previous comments.

To make all functions dynamically exported: -rdynamic.

For a single function to be always linked (even if not referenced) you need to add -u<function> to the link line.

To link all functions (even unreferenced) use --whole-archive. To return to the normal linking use --no-whole-archive

Upvotes: 0

yugr
yugr

Reputation: 21916

Unfortunately default behavior of GNU toolchain is to not export symbols from executables by default (as opposed to shared libraries which default to exporting all their symbols). You can use a big-hammer -rdynamic flag which tells linker to export all symbols from your executable file. A less intrusive solution would be to provide explicit exports file via -Wl,--dynamic-list when linking (see example usage in Clang sources).

Upvotes: 4

Related Questions