2

I am trying to write a simple program in C++ and I get a linker error that has been driving me crazy for the past 3 days. I have managed to get it down to a minimal (non) working example.

So I have in the same folder 3 files: main.cpp, ComGameTypes.h and ComGameTypes.cpp.

The contents are:

main.cpp:

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

int main() 
{
    GameState gs;
    gs.get(1);
    return 0;
};

ComGameTypes.h:

#pragma once
#include <iostream>
#include <array>

class GameState 
{
    public:
    std::array<int, 27> data;

    int get(int);
    GameState();
};

ComGameTypes.cpp:

#include "ComGameTypes.h"

inline int GameState::get(int i) 
{
    return data[i];
};

GameState::GameState() 
{
    std::cout << "Gamestate constructor running\n";
    for (int i = 0; i < 27; i++)
    {
        data[i] = 0;
    }
};

When I try to compile by g++ .\main.cpp .\ComGameTypes.cpp -o a this I get a linker error that there is an undefined reference to 'GameState::get(int)'.

The kicker is that if I add the line #include "ComGameTypes.cpp" in main.cpp and run g++ .\main.cpp -o a it compiles without errors! What causes this?

tst
  • 1,117
  • 2
  • 10
  • 21

0 Answers0