我试图使用 g++ 在 msys 上编译一个简单的 opengl 程序。令我惊讶的是,链接器提示 undefined reference :
$ g++ -mwindows -lopengl32 glut_md2.cpp
C:\Users\...\cceQtYAy.o:glut_md2.cpp:(.text+0x67a): undefined reference to `glGenTextures@8'
C:\Users\...\cceQtYAy.o:glut_md2.cpp:(.text+0x696): undefined reference to `glBindTexture@8'
....
谷歌搜索一段时间后,我发现问题出在 g++ 参数顺序上:
$ g++ glut_md2.cpp -mwindows -lopengl32
--- all ok! ---
有趣的是,g++ 中正确的参数顺序在第一个示例中。即:
$ g++ --help
Usage: g++.exe [options] file...
....
我错过了什么吗?为什么将选项移动到文件参数之后可以使编译成功?我在 Linux 上本地编译时从未遇到过这个问题...
最佳答案
我遇到过这个问题一两次,你应该把 -L 和 -l 放在命令行末尾。 g++ 不链接,它调用 ld 并传递参数,ld man:
The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again.
ld -o /lib/crt0.o hello.o -lc
关于reference - 奇怪的 g++ 链接行为取决于参数顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18827938/