How can a shared library (.so) call a function that is implemented in its loading program?

前端 未结 4 854
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 00:11

I have a shared library that I implemented and want the .so to call a function that\'s implemented in the main program which loads the library.

Let\'s say I have mai

4条回答
  •  囚心锁ツ
    2020-11-30 00:30

    1. Put your main function's prototype in a .h file and include it in both your main and dynamic library code.

    2. With GCC, simply compile your main program with the -rdynamic flag.

    3. Once loaded, your library will be able to call the function from the main program.

    A little further explanation is that once compiled, your dynamic library will have an undefined symbol in it for the function that is in the main code. Upon having your main app load the library, the symbol will be resolved by the main program's symbol table. I've used the above pattern numerous times and it works like a charm.

提交回复
热议问题