tags:

views:

93

answers:

2

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

A.h:

#include <iostream>

#ifndef _A_H
#define _A_H

class A {
 static A * a;
};

A * a = NULL;

#endif

However, when I include A.h in another file, such as:

#include "A.h"

class B {

};

I get 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'm using the Xcode default compiler on Mac OS X Snow Leopard.

Thanks,

helixed

+2  A: 

This line:

A * a = NULL;

needs to look like this:

A *A::a = NULL;

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

The definition of a static member must exist only once in your program. If you put this line in the header file, it would be included in every source file which includes it, leading to a duplicate symbol error.

interjay
Makes sense. Thanks.
helixed
+1  A: 

Because the global variable a is defined in both A.cpp and B.cpp. One public symbol only needs to be defined in one place. The rest can know what the content of that symbol by linking.

Move the A* a = NULL line away from A.h to A.cpp.

(BTW, to refer to the a in the class A, use A* A::a = NULL;, otherwise you're creating an a in the global namespace.)

KennyTM
Okay, I understand. Thanks.
helixed