SDL2 C程序编译链接报错:执行cc -lSDL2 -lGL *.o时SDL函数未定义引用
Ah, I’ve hit this exact linker quirk with GCC countless times—your issue isn’t missing -l flags, it’s the order of your arguments in the compile command.
Why this happens
GCC’s linker processes input files from left to right. When it encounters a library (like -lSDL2), it only uses it to resolve undefined references that have already been seen in the files before it. Since you put -lSDL2 and -lGL before your *.o object files, the linker hasn’t seen any of the SDL function calls in your code yet. By the time it gets to your object files, the libraries are already "done being checked," so those references stay undefined.
The fix
Swap the order: put your object files first, then the libraries. Run this command instead:
cc *.o -lSDL2 -lGL
Extra troubleshooting tips
If you still run into issues after fixing the order, try these:
- Use SDL’s built-in config tool to get the exact correct linker flags—run
sdl2-config --libsin your terminal, it’ll output something like-lSDL2main -lSDL2(some systems, especially Windows, require-lSDL2mainfor entry point handling). You can plug this directly into your command:cc *.o $(sdl2-config --libs) -lGL - Double-check that SDL2 is properly installed on your system. If you built it from source instead of using a package manager, you might need to add the
-Lflag to point to the directory where the SDL2 library files are stored:cc *.o -L/path/to/your/sdl2/lib -lSDL2 -lGL
内容的提问来源于stack exchange,提问作者user14430844

