Question

I can't understand something that causes LNK2005 errors that I've encountered. Assume that you have a class A:

File A.h:

    #ifndef A_H
    #define A_H

    class A{
    public:
        static foo(void);
    private:
        static bool m_someVar;
    };

    bool A::m_someVar = false;

    #endif

File A.cpp:

    #include "A.h"

    void A::foo(){
        m_someVar = true;
    }

The code above causes a LNK 2005 however the following code doesn't:

File A.h:

    #ifndef A_H
    #define A_H

    class A{
    public:
        static foo(void);
    private:
        static bool m_someVar;
    };

    #endif

File A.cpp:

    #include "A.h"

    bool A::m_someVar = false;

    void A::foo(){
        m_someVar = true;
    }

Can someone explain why is this happening even though I have include guards? Should I also add #pragma once?

Thanks in advance.

EDIT: here's the compilation error: "error LNK2005: "private: static bool GameManager::m_isGameOver" (?m_isGameOver@GameManager@@0_NA) already defined in Execution.obj"

Was it helpful?

Solution

include guards(both #ifndef and #pragma) doesn't work across compilation units, which is one of the reasons you should never ever ever define anything in a header file, only declare them. Except for templates of course.

A compilation unit is one .cpp-file and all included headers. Each .cpp create an object file containing a middle stage binary representation of the code, this is the compilation stage. These object files are then linked together in the linking stage. Since each .cpp is handled separately in c++ if you have "float foo;" in header.hpp and both a.cpp and b.cpp include header.hpp, how would the compiler know which foo you mean when running the application?

OTHER TIPS

A "static" variable inside a class declaration is actually a declaration for an extern variable that is in the scope of that class. Like every extern variable, it needs a definition in exactly one source file. Otherwise, the linker will complain about it.

You probably include the .h file from more than one source file, so you have more than one definition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top