Search code examples
c++linkerexternaldefinition

C++: unresolved external symbol thrown in Application.cpp (solution is at the end of the question for future readers)


So I'm writing an Input handler in C++ (and GLFW, but that doesn't matter), and one function that is not implemented in the header drop this error:

1>Input.obj : error LNK2001: unresolved external symbol "private: static class Input Input::instance" (?instance@Input@@0V1@A)

It is called like this in Application.cpp:

Input::GetInstance().Init(window);
Input::GetInstance().Update();

And the implementation is like this:

Input.h:

#ifndef INPUT_H_INCULDED
#define INPUT_H_INCLUDED

//Some includes

class Input
{
public:
    static Input& GetInstance();
  //some other non-static stuff
};

#endif

And the implementation in Input.cpp:

Input& Input::GetInstance()
{
return instance;
}

instance is a static member of Input.

I have glew, and glfw libs and includes in a folder called Dependencies in the solution directory. I included it in project properties, under C/C++\General\Additional Include Directories, and I also added $(SolutionDir)src, because I've placed every source file under src.

I then linked them, under Linker\General\Additional Library Directories, I added the location of the lib files, and under Linker\Input, I've added glfw3.lib, opengl32.lib, and glew3s.lib to the Additional Dependencies, and finally, added the GLEW_STATIC preprocessor definition. These are the only changes I've made in the project properties, and I use Debug, x86 configuration. The link to the source code:

https://github.com/Andrispowq/Prehistoric-Engine---C-

Edit: for any future readers: my problem was that I had to write

Input Input::instance;

somewhere in the code, in a cpp file, because instance is a static member of Input class. So, if you have a similar problem, make sure to check if you have static variables and if you have initialized them like this!


Solution

  • Your instance member, obviously need to be static member as well, from many reasons, for example to achieve singleton pattern, and especially cause you are returning by reference. By the way, if your static member function access some members of your class, that member need to be static as well. Exception will be if your static method, for example takes argument which can be particular instance of your class, or cast to it, and further using its parameter, static member function can possibly access or use methods or data members through that known instance, passed as argument to static member, but your GetInstance takes no argument. I hope this helps you to understand what your compiler telling you and that is, that compiler cant find symbol instance.