clinkerundefined-referencenmraylib

Why do I get an undefined reference to a symbol that is defined in the library I am linking?


I was trying to compile an unrelated project when I got an undefined reference when using a specific function of the Raylib library.

I was able to reproduce this behaviour using the following test.c

#include <raylib.h>

int main(){
        InitWindow(500,500, "test");
        
        int w = GetRenderWidth(); // undefined reference symbol
                                                                                
        while(!WindowShouldClose()){                                            
                BeginDrawing();                                                 
                ClearBackground(BLACK);                                  
                EndDrawing();                                                   
        }                                                                       
        CloseWindow();                                                          
        return 0;                                                               
} 

This code was compiled using the following command.

gcc test.c -o app -L/usr/local/lib -lraylib

The resulting output was

/usr/bin/ld: /tmp/ccxqgamX.o: in function `main':
code.c:(.text+0x27): undefined reference to `GetRenderWidth'
collect2: error: ld returned 1 exit status

Once I commented the offending line out however (// int w = GetRenderWidth();) The app compiled fine and also was able run succesfully.

I examined the libraylib.a library in my /usr/local/lib folder using

nm /usr/local/lib/libraylib.a | grep GetRenderWidth

This resulted in the following outputt:

0000000000027b1e T GetRenderWidth

From this I surmise that the symbol is actually present in the library I linked and thus my question. Why does my compiler (both gcc and clang) report an undefined reference on GetRenderWidth() but not on other symbols from the same library?


Solution

  • Turns out that /usr/local/lib also contained a shared version of the same library which my compilers linked with. This version did not contain the GetRenderWidth symbol which is what caused my confusion. I was able to force my compiler to use the static library by replacing -lraylib with -l:libraylib.a.