3

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?).

Bratchley
  • 460
  • 6
  • 17
  • You shouldn't need to link in any special libraries to get `stat`. Is this a cross compilation environment, or otherwise special build environment? – jxh May 16 '13 at 18:56
  • -On , n=0 no optimizations,n=1 ...n=3 all optimizations, -O0 removes all optimizations that could give the code an alternative form of execution – mf_ May 16 '13 at 18:56
  • No just a regular RHEL6 machine. – Bratchley May 16 '13 at 18:57
  • You are talking about the compilation of your `test-files.so` file, not the test binary, right? – jxh May 16 '13 at 18:57
  • They're both being built by the same Makefile in the same directory – Bratchley May 16 '13 at 18:58
  • Is the `test-files.so` being dynamically loaded (with `dlopen()`)? – jxh May 16 '13 at 18:59
  • @mf_ I tried `-O2` in case it was me turning off optimizations, but I get the same behavior. Any reference to `-O` when compiling seems to make stat work (the function outputs something different based on file status without re-compile). – Bratchley May 16 '13 at 18:59
  • @user315052 yes it is. – Bratchley May 16 '13 at 19:00

1 Answers1

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().

jxh
  • 69,070
  • 8
  • 110
  • 193