GLFW3看似随机的LNK2005错误

时间:2016-06-18 01:58:43

标签: c++ glfw

我因为看似没有理由而得到错误LNK2005,或者至少没有我能识别的错误。基本上,使用以下代码我可以毫无问题地编译。

test.h

#define GLEW_STATIC
#include <GL\glew.h>
#include <GLFW\glfw3.h>

namespace test
{
    //Objects and variables
    GLFWwindow* window;

    //Function prototypes
    bool Initialize();
}

TEST.CPP

#include "test.h"
#include <iostream>

bool test::Initialize()
{
    std::cout << "Initializing GLFW: OpenGL version 3.3 \n";

    //Initialize GLFW
    glfwInit();
    //Set window properties (version 3.3, core profile, not resizeable)
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    //Create Window
    window = glfwCreateWindow(800, 800, "Learn OpenGL", nullptr, nullptr);
    if (window = nullptr)
    {
        std::cout << "Failed to create GLFW window \n";
        glfwTerminate();
        return false;
    }

    return true;
}

int main()
{
    test::Initialize();

    return 0;
}

然而,当编译几乎完全相同的东西(http://pastebin.com/VpPep9pM)以及其他一些代码时,它会给出错误:

错误LNK2005“struct GLFWwindow * window”(?window @@ 3PAUGLFWwindow @@ A)已经在Main.obj中定义了OpenGL D:\ Users \ Matthew \ documents \ visual studio 2015 \ Projects \ OpenGL \ OpenGL \ System.obj

错误LNK2005“struct GLFWwindow * System :: window”(?window @ System @@ 3PAUGLFWwindow @@ A)已在Main.obj中定义OpenGL D:\ Users \ Matthew \ documents \ visual studio 2015 \ Projects \ OpenGL \ OpenGL \ System.obj

错误LNK1169找到一个或多个多重定义的符号OpenGL D:\ Users \ Matthew \ documents \ visual studio 2015 \ Projects \ OpenGL \ Debug \ OpenGL.exe

所以,我想知道导致错误的原因,我认为它与“上下文”有关。

1 个答案:

答案 0 :(得分:0)

在头文件中,当您需要在标头中声明并在一个源文件中定义时,您将定义变量。

在test.h中

namespace test {
    extern GLFWwindow* window;
}

和main.cpp

namespace test {
    GLFWwindow* window;
}

如果标题中没有extern,则在包含它的每个源文件中创建一个test::window实例,如果有两个或更多定义,则会出现问题。