【问题标题】:LNK 2019 "Unresolved External Symbol" Error (C++ OpenGL)LNK2019“未解析的外部符号”错误(C++ OpenGL)
【发布时间】:2015-12-11 08:26:47
【问题描述】:

我对 C++ 比较陌生,在文件中创建类时遇到了一些问题。我正在尝试从单独的类 Shader 调用构造函数,并使用所述类中的方法。但是,每当我尝试构建解决方案时,都会收到以下错误:

Error   2   error LNK2019: unresolved external symbol "public: void __thiscall Shader::Use(void)" (?Use@Shader@@QAEXXZ) referenced in function _main    
Error   1   error LNK2019: unresolved external symbol "public: __thiscall Shader::Shader(char const *,char const *)" (??0Shader@@QAE@PBD0@Z) referenced in function _main

我知道项目属性链接器或渲染系统没有任何问题,因为我以前用我当前的配置渲染过东西,所以我认为它一定与代码有关,但我想不通出:

main.cpp

#include <iostream>

// GLEW
#define GLEW_STATIC
#include <GL/glew.h>

// GLFW
#include <GLFW/glfw3.h>

// Other includes
#include "Shader.h"

int main ()
{

(... Window Setup ...)


// Build and compile shader program
Shader shaders ("shader.vs", "shader.frag");


(... Set up vertex data (and buffer(s)) and attribute pointers ...)

// Game loop
while(!glfwWindowShouldClose (window))
{
    glfwPollEvents ();

    ourShader.Use ();

(... Draw triangle ...)

    glfwSwapBuffers (window);
}
(... De-allocate all resources ...)

(... Terminate window ...)
return 0;
}

着色器.h

#ifndef SHADER_H
#define SHADER_H

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

#include <GL/glew.h>

class Shader
{
public:

GLuint Program;
Shader(const GLchar* vertexPath, const GLchar* fragmentPath);
void Use ();

};

#endif

着色器.cpp

#ifndef SHADER_H
#define SHADER_H

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

#include <GL/glew.h>

#include "Shader.h"

class Shader
{
public:
GLuint Program;
Shader::Shader(const GLchar* vertexPath, const GLchar* fragmentPath)
{
    (... 1. Retrieve the vertex/fragment source code from filePath ...)

    (... 2. Compile shaders ...)

    (... 3. Link shader program ...)

    (... 4. Delete shaders after usage ...)
}

void Shader::Use ()
{
    (... Use current shader program ...)
}
};

#endif

任何帮助将不胜感激。如果需要更多代码,我可以提供。提前致谢!

【问题讨论】:

  • 你真的在编译 Shader.cpp 吗?
  • 您应该只在标题中定义一次类。成员的定义放在源文件中。

标签: c++ opengl linker-errors glfw


【解决方案1】:

首先,如果编译成功,那是因为shader.cpp 中的包含保护删除了错误代码。其次,如果您从 shader.cpp 中删除包含保护(您应该这样做),这将不会编译,因为该类在 shader.cpp 中声明了两次(通过 #include "Shader.h")。反过来又会发生链接错误,因为 main.cpp 没有与 shader.cpp 的编译版本链接。

  1. shader.cpp 中删除包含保护 - 因为您在 shader.h 中定义了 SHADER_H,所以预处理器会在 shader.cpp 到达编译器之前删除所有代码
  2. 从 shader.cpp 中删除类声明,但保留着色器类的所有成员的定义。保持shader.cpp 简单,就像这样:

    #include "shader.h"
    
    Shader::Shader(const GLchar* vertexPath, const GLchar* fragmentPath)
    { /*..body */ }
    
    Shader::use()
    { /*..body */ }
    
  3. 确保将 main 链接到着色器的编译版本,例如g++ main.cpp shader.o,假设着色器是单独编译的,例如g++ -c shader.cpp

【讨论】:

  • 做到了。谢谢!
猜你喜欢
  • 2018-07-04
  • 1970-01-01
  • 2012-10-31
  • 2012-08-31
相关资源
最近更新 更多