Search code examples
c++visual-studio-2010linker-errorsunresolved-externallnk2019

Unresolved External Symbol with extremely simple class (VS2010)


I am holily convinced that this is an extremely basic thing that every living human being is perfectly able to perform, yet somehow it's not working for me. The FAQ and many other threads/questions found through Google have not fixed this for me.

The situation is as follows: I have one Visual Studio 2010 project. This project is located in a Visual Studio 2010 solution. The project has the following files:

add.h:

class Adder {
public:
    static int add(int i1, int i2);
};

add.cpp:

class Adder {
public:
    static int add(int i1, int i2) {
        return i1 + i2;
    }
};

main.cpp:

#include "add.h"

int main() {
    Adder::add(5, 6);
    return 0;
}

When attempting to run this code, which looks fairly basic to me, I get the following linker error:

main.obj : error LNK2019: unresolved external symbol "public: static int __cdecl Adder::add(int,int)" (?add@Adder@@SAHHH@Z) referenced in function _main

From what I could gather, this implies that the linker could not find the implementation for Adder::add(). However, the files are in exactly the same project, the generated .obj files are in exactly the same folder, and every single tutorial I've read on the subject of classes and header files tells me that this should work.

I've tried the following potential solutions thus far:

  • Add the project's own folder to additional includes/dependencies/sources/whatevers
  • Add extern identifiers to various things
  • Use a seperate namespace
  • Various other small adjustments in the hope they would work

So I guess my problem boils down to: How can I get the linker to notice the add.cpp file? Any help is appreciated, I've spent several hours on this now without success, while this seems like an extremely basic thing to me.


Solution

  • The following defines a whole new class

    //add.cpp:
    class Adder {
    public:
        static int add(int i1, int i2) {
            return i1 + i2;
        }
    };
    

    different from the one in the header, available only to this translation unit ("add.cpp").

    What it should contain is:

    //add.cpp
    #include "add.h"
    int Adder::add(int i1, int i2) {
        return i1 + i2;
    }
    

    This implements the method defined in the class from the header add.h.