0
votes

I'm getting the error LNK2005 for seemingly no reason, or at least none that can I can identify. Essentially, using the following code I can compile without issue.

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;
}

However, when compiling nearly the exact same thing (http://pastebin.com/VpPep9pM), along with some other code, it gives the errors:

Error LNK2005 "struct GLFWwindow * window" (?window@@3PAUGLFWwindow@@A) already defined in Main.obj OpenGL D:\Users\Matthew\documents\visual studio 2015\Projects\OpenGL\OpenGL\System.obj

Error LNK2005 "struct GLFWwindow * System::window" (?window@System@@3PAUGLFWwindow@@A) already defined in Main.obj OpenGL D:\Users\Matthew\documents\visual studio 2015\Projects\OpenGL\OpenGL\System.obj

Error LNK1169 one or more multiply defined symbols found OpenGL D:\Users\Matthew\documents\visual studio 2015\Projects\OpenGL\Debug\OpenGL.exe

So, I would like to know what causes the errors, I'm assuming it has something to do with the "context".

1

1 Answers

0
votes

In your header file, you are defining you variable, when it needs to be declared in the header and defined in one source file.

In test.h

namespace test {
    extern GLFWwindow* window;
}

and in main.cpp

namespace test {
    GLFWwindow* window;
}

Without the extern in the header, you create one instance of test::window in every source file that includes it, which is a problem if there are two or more definitions.