13

I have an executable and a dynamic library (.so). The library exports some symbols and executable calls it successfully. But I want to make possible to library call executable's functions. I've tried to do following in executable:

//test
extern "C" void print(const char * str) {
    std::cout << str << std::endl;
}

and this in library:

extern "C" void print(const char *);

but when i call dlopen in executable (to load the library) it returns error undefined symbol: print. how can i fix it?

2 Answers 2

14

In Linux/ELF you can pass the -export-dynamic option to the linker (-rdynamic on the compiler driver gcc) so symbols from the executable are exported to shared objects.

You'd have a dummy print implementation in your library, which would be shadowed by the implementation on your executable, since the executable is usually searched before shared objects for symbol resolution.

This has the disadvantage that it's not very fine-grained, you could end up overriding some symbol you didn't intend to. The finer-grained option would be to create a list of symbols to be exported as:

{
    print;
    <other symbols>
};

and pass that list to the linker, e.g. from gcc: -Wl,--dynamic-list=<file with list of symbols>

Sign up to request clarification or add additional context in comments.

3 Comments

@milo: I've added a more fine-grained way of exporting symbols from the executable.
thanks a lot! i think i'd better read "dso howto" to get more comprehesive knowledges in shared objects.
A few word to the other major platforms would be nice.
4

An easier way to achieve this is to have the executable register a function for later use by the library, the library stores a pointer to the function, and may call it at a later time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.