Static variables of the same class in C ++

I am trying to create a class that contains a static pointer to an instance of itself. Here's an example:

hijri:

#include <iostream>

#ifndef _A_H
#define _A_H

class A {
 static A * a;
};

A * a = NULL;

#endif

      

However, when I include Ah in another file like:

#include "A.h"

class B {

};

      

I am getting the following error:

ld: duplicate symbol _a in /Users/helixed/Desktop/Example/build/Example.build/Debug/Example.build/Objects-normal/x86_64/B.o and /Users/helixed/Desktop/Example/build/Example.build/Debug/Examplebuild/Objects-normal/x86_64/A.o

      

I am using the default Xcode compiler for Mac OS X Snow Leopard.

+2


a source to share


2 answers


This line:

A * a = NULL;

      

should look like this:



A *A::a = NULL;

      

And you need to move it out of the header file and put it in the source (.cpp) file.

A static member definition must exist only once in your program. If you put this line in a header file, it will be included in every source file that includes it, resulting in a duplicate symbol error.

+5


a source


Since the global variable is a

defined in A.cpp

both B.cpp

. One public symbol should only be defined in one place. The rest can know what the contents of this symbol are by linking.

Move the line A* a = NULL

away from A.h

to A.cpp

.



(BTW, to reference a

in a class a

, use A* A::a = NULL;

, otherwise you create a

in the global namespace.)

+2


a source







All Articles