Search code examples
c++unresolved-external

LNK2019 - Unresolved external symbol


I've tried to find a solution to this problem by looking through the old questions and answers, but I can't spot what's wrong in my case. I get the following error:

Error 66 error LNK2019: unresolved external symbol "public: static class PhysicsBody *
__cdecl PhysicsBody::createBox(float,float,enum PhysicsBodyType,float)"
(?createBox@PhysicsBody@@SAPAV1@MMW4PhysicsBodyType@@M@Z) referenced in function
"public: __thiscall Enemy::Enemy(void)" (??0Enemy@@QAE@XZ)

The weird thing is, the code file is there, both .H and .CPP, and they are included in the solution and compiled correctly. Here's the code files:

// Enemy.h
#pragma once

class Enemy {
public:
    Enemy();
private:
    PhysicsBody* m_body;
};

// Enemy.cpp
#include "Enemy.h"
#include "PhysicsBody.h"

Enemy::Enemy() {
    m_body = PhysicsBody::createBox(1.f, 1.f, PhysicsBodyType::Dynamic);
}

// PhysicsBody.h
#pragma once

enum PhysicsBodyType {
    Static, Dynamic, Kinematic
};

class PhysicsBody {
public:
    static PhysicsBody* createBox(float width, float height, PhysicsBodyType type, float mass = 1.f);
private:
    PhysicsBody();
};

// PhysicsBody.cpp
#include "PhysicsBody.h"

PhysicsBody::PhysicsBody() {

}

PhysicsBody* PhysicsBody::createBox(float width, float height, PhysicsBodyType type, float mass) {
    return new PhysicsBody();
}

(I have cropped out some non-relevant code here.)

I've literally skimmed through the code tens of times and cannot spot anything wrong with it. I have similar code throughout my project and everything else works. For some reason, this PhysicsBody class causes these problems. I've checked that it's included in the project / solution, the file type is C/C++ Code, it's not marked as content and overall it should be working.


Solution

  • The problem was quite probably caused by a faulty VS project file. I copied the contents of PhysicsBody.h / .cpp files, deleted both files, created new files and pasted the original contents. All code is exactly the same and it works now, so I conclude that it's a VS-related bug.