问题
Tried to do a search, but didn't find anything. Whenever I try to compile a shared object and the test binary that links to it I get this error:
[root@hypervisor test-files]# ./test
./test: symbol lookup error: ./test-files.so: undefined symbol: stat
[root@hypervisor test-files]#
After playing around with it I found that if I feed -O to gcc during the compile, stat() starts working as expected. I haven't been able to find any indication online as to why -O of all things fixes a problem with an undefined symbol (or does it just mask an error instead of fixing it?).
回答1:
In all likelihood, the optimization triggered removal of unreachable code, removing the need for the symbol altogether.
When you built the test-files.so shared object, you likely did not use the C compiler but invoked ld directly. Thus, any library dependencies that test-files.so had would not be present. Loading the file dynamically would make it attempt to resolve the symbols with those already available within your test binary, and it could not be found.
Compiling with the optimization removed the unreachable code that called stat, and so the symbol did not need to be resolved on the call to dlopen().
来源:https://stackoverflow.com/questions/16595201/why-does-o-to-gcc-cause-stat-to-resolve