Search code examples
c++staticglobal-variableslinkage

Static variable link error, C++


Consider this code.

//header.h
int x;

//otherSource.cpp
#include "header.h"

//main.cpp
#include "header.h"
...
int main()
{

}

In this case compiler erred with the message. "fatal error LNK1169: one or more multiply defined symbols found"

but when I add static before x, it compiles without errors.

And here is the second case.

//header.h

class A
{
public:
    void f(){}
    static int a;
};

int A::a = 0;

/otherSource.cpp
#include "header.h"

//main.cpp
#include "header.h"
...
int main()
{

}

In this case compiler again erred with multiple declaration.

Can anybody explain me the behavior we static variables in classes and in global declarations?? Thanks in advance.


Solution

  • The issue with the static member variable is that you have the definition occur in the header file. If you #include the file in multiple source files, you have multiple definitions of the static member variable.

    To fix this, the header file should consist only of this:

    #ifndef HEADER_H
    #define HEADER_H
    // In the header file
    class A
    {
    public:
        void f(){}
        static int a;
    };
    #endif
    

    The definition of the static variable a should be in one and only one module. The obvious place for this is in your main.cpp.

    #include "header.h"
    int A::a = 0;  // defined here
    int main()
    {
    }