Search code examples
c++header-filessfml

One time included .h functions already defined in main.obj


Ok so, simply said : I've included a .h into another .h and i get a compilation error telling me that the functions are already defined in main.obj But, well i've only included Graphics.h one time so how can it be possible that main.obj also defined the Graphics.h functions ? I got an Error LNK2005 "Already defined in main.obj".

Graphics.h contain functions that many others files will need, but for the moment we have a problem with just one file so I'd like to fix that first.

EDIT : SOLVED by spliting the header, i kept the header for the functions prototypes and I created a new Graphics.cpp for the functions definition

Here are the most concerned files, I've commented the files content so it is readable. If I'm wrong by commenting please tell me and I'll put it on pastebin or something like that

main.cpp

#include "main.h"

using namespace std;

int main()
{
    sMainData data = {};
    main_Initialize(data);

    while (data.config.window.isOpen())
    {
        main_Event(data);
        main_Update(data);
        main_Draw(data);
    }
    return 0;
}

main.h file :

#ifndef MAIN_H
#define MAIN_H

#include <SFML/Graphics.hpp>
#include "PlayerClass.h"

// Structures...
// Prototypes...
// Functions...

#endif // !MAIN_H

PlayerClass.h file :

#ifndef PLAYERCLASS_H
#define PLAYERCLASS_H

#include "AliveClass.h" // Including the mother

#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include "Graphics.h" // <-- So here we have our man

//Class definition

#endif // !1

Graphics.h file :

#ifndef GRAPHICS_H
#define GRAPHICS_H

#include "SFML/Graphics.hpp"

// Prototypes...
// Functions...

#endif // !GRAPHICS_H

Solution

  • You didn't provide a minimal reproducible example, but my best guess is, you have some function implemented in the header file, while ending up including that header, either directly or indirectly, in more than one cpp file. The result is exactly the same function with exactly the same signature, being compiled in both cpp files, which causes the linker to complain.

    Solutions:

    • Move the function out of the header and into its own cpp file (probably the best)
    • Find a way to only include the header in one single cpp file (probably the second best in case the header isnt yours and you don't want to touch it)
    • Make that function inline (probably the easiest, but technically the worst)