为什么我不能正确链接 opengl 库? Windows、mingw、命令行

问题描述

所以基本上我想要做的是在没有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)

项目层次结构:

Picture of the project hierarchy in VSCode

当我运行 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

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

解决方法

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

,

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

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

到:

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