Search code examples
c++classstaticmembers

C++ static bool variable


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"


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?