0

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.

1
  • The definition (where you initialize the static variabe) should be in one and only one source file. Don't place it in a header file. Commented Apr 26, 2015 at 15:33

2 Answers 2

3

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()
{
}
Sign up to request clarification or add additional context in comments.

Comments

2

Declare x as extern in header.h to tell the compiler that x will be defined somewhere else:

extern int x;

Then define x once in the source file which you think is most fitting.
For example in otherSource.cpp:

int x = some_initial_value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.