I want to separate Game class into header and source. To do that I need to be able to define the functions outside the class, but, strangely, I can't!
main.cpp
#include "app.hpp"
int main ()
{
Game game(640, 480, "Snake");
game.run();
return 0;
}
app.hpp
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
class App
{
friend class Game;
public:
App(const int X, const int Y, const char* NAME);
void run(void);
private: // Variables
sf::RenderWindow window;
sf::Event event;
sf::Keyboard kboard;
};
#include "game.hpp"
And now the question part.
game.hpp.
class Game // this snippet works perfectly
{
public:
Game(const int X, const int Y, const char* TITLE) : app(X, Y, TITLE)
{ /* and the initialization of the Game class itself... */}
void run()
{ app.run(); /* And the running process of Game class itself*/};
private:
App app;
};
class Game // this snippet produces compiler errors of multiple definitions...
{
public:
Game(const int X, const int Y, const char* TITLE);
void run();
private:
App app;
};
Game::Game(const int X, const int Y, const char* TITLE) : app(X, Y, TITLE) {}
void Game::run() { app.run(); } // <<< Multiple definitions ^^^
Why?
Because you are defining the functions in the header file and when you include the header in translation units a copy of the function is created in each translation unit, thus leading to multiple definitions and violation of one definition rule.
You can define the functions separately but in a cpp file. You declare functions in header file and define them in source cpp file.
The only standard compliant way to bypass one definition rule is to use
inline
functions. When you define the functions inside the class body, they are implicitlyinline
and the program can successfully bypass one definition rule and the multiple definition linking error.