【问题标题】:Why can't i properly link opengl libraries? (Windows, mingw, command line)为什么我不能正确链接 opengl 库? (Windows、mingw、命令行)
【发布时间】:2021-02-23 07:51:07
【问题描述】:

所以基本上我想要做的是在没有 VS 的 windows pc 上设置 opengl。这很痛苦,因为这个星球上每个该死的教程都使用 Visual Studio,但我只是讨厌它,所以我不会使用它。 我所做的是下载所有必要的库、设置项目、创建主文件而不是 Makefile。 main.cpp:

#define FREEGLUT_STATIC
#include <windows.h>
#include <GL/glut.h>

int main(int argc, char** argv){
    glutInit(&argc,argv);
    glutCreateWindow("hello");
    glutInitWindowSize(400,400);
    glutMainLoop();
    return 0;
}

我的 Makefile:

INCL_DIR = include
SRC_DIR = src
LIB_DIR = lib
BUILD_DIR = build
OUTPUT_NAME = graph.exe

CXX = g++
CXXFLAGS = -I$(INCL_DIR) 
LDFLAGS = -L$(LIB_DIR) -lfreeglut -lglew32 -lopengl32 -lgdi32 -lwinmm

SRCS := $(wildcard $(SRC_DIR)/*.cpp)
OBJS := $(SRCS:%.cpp=%.o)

$(OUTPUT_NAME): $(OBJS)
    $(CXX) -o $(BUILD_DIR)/$(OUTPUT_NAME) $(OBJS) $(CXXFLAGS)

clean:
    del /f $(SRC_DIR)\*.o
    del /f $(BUILD_DIR)\$(OUTPUT_NAME)

项目层次结构:

当我运行 make 时会发生什么:

PS C:\programming\projects\opengl_base> make
g++ -Iinclude    -c -o src/main.o src/main.cpp
g++ -o build/graph.exe src/main.o -Iinclude 
src/main.o:main.cpp:(.text+0x23): undefined reference to `__glutInitWithExit'
src/main.o:main.cpp:(.text+0x46): undefined reference to `__glutCreateWindowWithExit'
src/main.o:main.cpp:(.text+0x68): undefined reference to `__glutCreateMenuWithExit'
src/main.o:main.cpp:(.text+0xad): undefined reference to `glutInitWindowSize'
src/main.o:main.cpp:(.text+0xb2): undefined reference to `glutMainLoop'
collect2.exe: error: ld returned 1 exit status
make: *** [graph.exe] Error 1

我的理解是,这些库由于某种原因根本没有链接。但为什么?请帮帮我

【问题讨论】:

  • 首先,-L...-l... 不属于 CXXFLAGS,并且在编译时会被忽略(但在链接时不会)。通常,您有一个名为LDFLAGS 的单独变量,用于在链接时代替CXXFLAGS。接下来,谷歌搜索显示__imp_timeBeginPeriod 来自“winmm”库,因此添加-lwinmm。接下来,__imp_glPushAttrib 来自 -lopengl32(因为您已经拥有它,它可能相对于其他 -l... 标志定位不正确,请尝试将其移至末尾)。
  • @HolyBlackCat 感谢您的回答。正如你所说,我已经编辑了所有内容,看起来好多了。现在我处于尝试操纵他人的 CLion 项目时达到的状态。 (至少现在我很自豪我从头开始做到这一点)
  • @HolyBlackCat Nvm 我很愚蠢,我没有正确更新 Makefile。现在它编译并运行。谢谢你

标签: c++ opengl mingw static-libraries static-linking


【解决方案1】:

所以对于以后偶然发现这个问题的任何人:每当您尝试链接更多库并且它们相互依赖时,请稍微弄乱它们的顺序。

【讨论】:

  • 是的,您将它们指定给链接器的顺序很重要。回到“旧”时代,您有时甚至不得不多次将它们放在链接器线上。尝试切换到 LLVM 的 lld 或 GNU gold 链接器。
【解决方案2】:

链接 exe 文件的行有编译器标志而不是链接器标志 init。 要在Makefile 中解决此问题,请更改:

        $(CXX) -o $(BUILD_DIR)/$(OUTPUT_NAME) $(OBJS) $(CXXFLAGS)

到:

        $(CXX) -o $(BUILD_DIR)/$(OUTPUT_NAME) $(OBJS) $(LDFLAGS)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 2017-01-02
    • 2019-01-16
    相关资源
    最近更新 更多