Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

c - how to call function in executable from my library?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...