1

I have a method defined in a header file and declared in a source file. When I call the method, the linker throws an error saying it can't find the error.

Error 1 error LNK2019: unresolved external symbol "public: class Chunk * __thiscall World::getChunk(short,short)" (?getChunk@World@@QAEPAVChunk@@FF@Z) referenced in function _main

Error 2 error LNK1120: 1 unresolved externals

World.h:

#pragma once
#include <map>
#include <vector>
#include "Chunk.h"

class World {
public:
    World();
    ~World();
    void generateChunk(short x, short z);
    inline Chunk* getChunk(short x, short z);
private:
    std::vector< std::vector<Chunk*> > loadedChunks;
};

World.cpp:

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

World::World() : loadedChunks(1, std::vector<Chunk*>(1)) {}

World::~World() {
    for(unsigned short x = loadedChunks.size(); x > 0; --x)
        for(unsigned short z = loadedChunks[x].size(); z > 0; --z) {
            std::cout << "Destructed" << std::endl;
            delete loadedChunks[x][z];
        }
}

void World::generateChunk(short x, short z) {
    Chunk chunk(x, z);
    delete loadedChunks[x][z];
    chunk.generate();
    loadedChunks[x][z] = &chunk;
}

Chunk* World::getChunk(short x, short z) {
    return loadedChunks[x][z];
}

Later when I run:

World world;
world.generateChunk(0, 0);
world.getChunk(0, 0);

It won't compile / link with the above mentioned error messages.

Jeroen
  • 15,257
  • 12
  • 59
  • 102

3 Answers3

3

You must include the function definition in the header file since you marked it as inline.

inline Chunk* getChunk(short x, short z);
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • I don't quite understand, it is defined in the header file. – Jeroen Jul 28 '13 at 16:04
  • 1
    @Binero: The code you have shown, defines it in `World.cpp`, it should be defined in `World.h`. – Alok Save Jul 28 '13 at 16:05
  • So when I make inline methods they should be defined in the same file as the declaration? :O – Jeroen Jul 28 '13 at 16:06
  • @Binero: Yes, ofcourse! With `inline` you tell the compiler to substitute the function call with it's body during compilation. Since each TU is compiled separately unless the compiler sees the definition it cannot perform the substitution. – Alok Save Jul 28 '13 at 16:08
  • Never knew that. I have in the same application multiple instances where this is not the case, and it still works. :o – Jeroen Jul 28 '13 at 16:15
2

getChunk() is defined inline - therefore the linker will not find it.

(Edit / Added). This fix should do:

inline Chunk* getChunk(short x, short z) {
    return loadedChunks[x][z];
}

and remove the implementation from the cpp file.

Andreas Florath
  • 4,418
  • 22
  • 32
1

Already answered here: inline function linker error

You must declare the body in the header because the compiler must know what it is inliling

Community
  • 1
  • 1
Caian
  • 440
  • 4
  • 15