How is function main() inside a shared object (.so) taken care of by the linker?

亡梦爱人 提交于 2019-12-08 17:30:36

问题


Suppose I have

  • an object file (source.o) without function main.

  • a shared object (libmain.so) with function main.

How will the linker take care of the entry point when both are linked dynamically to create binary source.bin?


回答1:


Whenever you have a dynamic linked program, there are several "entry points" involved. The first is in entry point of the dynamic linker itself, e.g. /lib/ld-linux.so.2 (on Linux/x86) or similar. The dynamic linker runs first, resolving all symbol names to their definitions (regardless of whether the definitions are in the main program or a library), then passes execution to the second entry point in the main program binary. This is not main but part of the "C runtime" (thus crt.o and similar names) that takes care of some pre-main stuff (like C++ ctors, setting up the pointer to the environment variables, and constructing the right arguments for main). This code ends with (the equivalent of) exit(main(argc, argv)); which will use the relocated (by the dynamic linker) addresses of both exit and main.




回答2:


main() is just like any other function however in hosted envrionment it is treated as the logical entry point of an c/c++ program. So there is nothing special with regards to linking of main() as an function.



来源:https://stackoverflow.com/questions/9807194/how-is-function-main-inside-a-shared-object-so-taken-care-of-by-the-linker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!