C++ OpenGL项目编译报错:头文件找不到及未定义引用问题
OpenGL项目编译/链接错误解决指南
问题1:头文件找不到(shaderClass.h: No such file or directory)
你的shaderClass.h存放在{workspaceFolder}/include/header files目录下,但编译命令里的-I参数仅指定了${workspaceFolder}/include,编译器只会在include根目录下检索头文件,不会自动递归子目录header files。
解决方法二选一:
- 修改编译参数:在
tasks.json的args里添加子目录的包含路径:"args": [ "-g", "-std=c++17", "-I${workspaceFolder}/include", "-I${workspaceFolder}/include/header files", // 新增该行 "-L${workspaceFolder}/lib", "${workspaceFolder}/src/main.cpp", "${workspaceFolder}/src/glad.c", "-lglfw3dll", "-o", "${workspaceFolder}/main.exe" ] - 修改头文件引用路径:在
main.cpp里补全子目录路径:#include "header files/shaderClass.h" #include "header files/VBO.h" #include "header files/VAO.h" #include "header files/EBO.h"
问题2:自定义类成员函数未定义引用(collect2.exe: error: ld returned 1 exit status)
你仅编译了main.cpp和glad.c,但VAO::LinkVBO这类成员函数的实现代码(比如VAO.cpp、VBO.cpp、shaderClass.cpp)未加入编译流程,链接器找不到函数定义导致报错。
解决方法:
把所有自定义类的源文件添加到编译命令的源文件列表中,示例:
"args": [ "-g", "-std=c++17", "-I${workspaceFolder}/include", "-I${workspaceFolder}/include/header files", "-L${workspaceFolder}/lib", "${workspaceFolder}/src/main.cpp", "${workspaceFolder}/src/glad.c", "${workspaceFolder}/src/VAO.cpp", // 加入实现文件 "${workspaceFolder}/src/VBO.cpp", "${workspaceFolder}/src/EBO.cpp", "${workspaceFolder}/src/shaderClass.cpp", "-lglfw3dll", "-o", "${workspaceFolder}/main.exe" ]
附用户提供的相关代码/配置:
main.cpp({workspaceFolder}/src/main.cpp)
#include <glad/glad.h> // 正常 #include <GLFW/glfw3.h> // 正常 #include <iostream> #include "math.h" #include <random> #include "shaderClass.h" // 报错 #include "VBO.h" #include "VAO.h" #include "EBO.h" // 后续代码...
shaderClass.h({workspaceFolder}/include/header files/shaderClass.h)
#ifndef SHADER_CLASS_H #define SHADER_CLASS_H #include"glad/glad.h" // 其他系统头文件 // 代码实现 #endif
tasks.json编译参数
"command": "C:/msys64/ucrt64/bin/g++.exe", "args": ["-g","-std=c++17","-I${workspaceFolder}/include","-L${workspaceFolder}/lib","${workspaceFolder}/src/main.cpp","${workspaceFolder}/src/glad.c","-lglfw3dll","-o","${workspaceFolder}/main.exe"]
c_cpp_properties.json配置
"includePath": ["${workspaceFolder}/**","${workspaceFolder}/include/header files"]
实际编译命令示例
cmd /c chcp 65001>nul && C:/msys64/ucrt64/bin/g++.exe -g -std=c++17 -IC:\Users\calex\Fih/include -LC:\Users\calex\Fih/lib C:\Users\calex\Fih/src/main.cpp C:\Users\calex\Fih/src/glad.c -lglfw3dll -o C:\Users\calex\Fih/main.exe
内容的提问来源于stack exchange,提问作者i can eat a water
相关产品推荐
相关产品推荐

