reference - 奇怪的 g++ 链接行为取决于参数顺序

标签 reference g++ undefined msys

我试图使用 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/

相关文章:

objective-c - 将值传递给属性的正确方法是什么?

c++ - 三元运算符 : Compiler does not emit return reference of local variable warning

C++ 概念和 std::cout

g++ - 如何禁用 g++ 中的特定警告

javascript - 为什么 typescript 提示对象的键是未定义的,即使前一个命令为该键设置了一个值?

c - 访问通过引用接收的结构体的成员

c++ - 将 --whole-archive 链接器选项与 CMake 和具有其他库依赖项的库一起使用

c - 对未设置的值使用 IEEE754 浮点 NaN 是个好主意吗?

javascript - jQuery:div 的选择器存储在变量中时未定义

c# - .NET 中的对象引用有多大?