0

I try to follow a tutorial to create a simple ECS project but I have some trouble when I try to compile.

my code:

main.cpp

#include "Utils.h"

using namespace std;

int main()
{
    cout << "TransformComponent ID: " << GetId<TransformComponent>() << std::endl;
    return 0;
}

Utils.h

#ifndef UTILS_H_
#define UTILS_H_
#include <iostream>


extern int s_componentCounter;

struct TransformComponent
{
    float position{ 1.0f };
    float rotation{ 2.0f };
};

template <class T>
int GetId();

#endif

Utils.cpp

#include "Utils.h"
int s_componentCounter = 0;



template <class T>
extern int GetId() {
    static int s_componentId = s_componentCounter++;
    return s_componentId;
}

I compile with this:

g++ Utils.cpp TestECS.cpp

and I get this:

main.cpp:(.text+0x6f): undefined reference to `int GetId<TransformComponent>()'
collect2.exe: error: ld returned 1 exit status
  • It looks like the linker cant find instantiation for your template. There are some workarounds to seperate implementation from the template. Generally, template instantiation should be implemented in the header file. – kobi Nov 17 '21 at 05:47

0 Answers0