Moving to different Linux build system, getting error: undefined symbol: stat

后端 未结 1 884
遥遥无期
遥遥无期 2021-01-12 16:48

This may just be an issue with the build system I am migrating to, but I\'ll include differences in the two systems and how I encountered the problem.

My old build s

相关标签:
1条回答
  • 2021-01-12 17:48

    The problem you are facing is most likely the result of building your shared library with ld. User-level code on UNIX systems should never use ld directly. You should use the compiler driver (g++ in your case) to perform the link instead.

    Example:

    // t.c
    #include <sys/stat.h>
    
    void fn(const char *p)
    {
      struct stat st;
      stat(p, &st);
    }
    
    gcc -fPIC -c t.c
    ld -shared -o t.so t.o
    nm t.so | grep stat
                 U stat       ## problem: this library is not linked correctly
    

    Compare to correctly linked library:

    gcc -shared -o t.so t.o
    nm t.so | grep stat
    
    0000000000000700 t stat
    0000000000000700 t __stat
                     U __xstat@@GLIBC_2.2.5
    

    To find where the above local stat symbol came from, you could do this:

    gcc  -shared -o t.so t.o -Wl,-y,stat
    t.o: reference to stat
    /usr/lib/x86_64-linux-gnu/libc_nonshared.a(stat.oS): definition of stat
    

    Finally, the reason U stat disappears with optimization:

    gcc -E t.c | grep -A2 ' stat '
    
    extern int stat (const char *__restrict __file,
      struct stat *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
    
    gcc -E t.c -O | grep -A2 ' stat '
    
    __attribute__ ((__nothrow__ , __leaf__)) stat (const char *__path, struct stat *__statbuf)
    {
       return __xstat (1, __path, __statbuf);
    

    That's right: you get different preprocessed source depending on the optimization level.

    0 讨论(0)
提交回复
热议问题