打算建一個類,每生成一個對象就自動獲取一個惟一的ID。ide
main.cppui
#include "stdio.h"
#include "CNode.h"
int main(int argc, char** argv)
{
CNode cNode1;
CNode cNode2;
CNode cNode3;
printf("cNode1.ID = %d\n ", cNode1.ulID);
printf("cNode2.ID = %d\n ", cNode2.ulID);
printf("cNode3.ID = %d\n ", cNode3.ulID);
}
spa
CNode.h對象
#ifndef CNODE__
#define CNODE__
class CNode {
public:
CNode();
virtual ~CNode();
static unsigned int ulIDCreator;
unsigned int ulID;
};
unsigned int CNode::ulIDCreator = 0;
#endif
ip
CNode.cppit
#include "CNode.h"
CNode::CNode(){
ulID = ++ulIDCreator;
}
CNode::~CNode(){
}io
*** Internal Builder is used for build ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -osrc\CNode.o ..\src\CNode.cpp
g++ -oArctic.exe src\Main.o src\CNode.o
src\CNode.o: In function `ZN5CNodeC1Ev':
E:/EclipseWorkspace/Arctic/Debug/../src/CNode.cpp:9: multiple definition of `CNode::CNode()'
src\Main.o:E:/EclipseWorkspace/Arctic/Debug/../src/Main.cpp:13: first defined here
src\CNode.o: In function `ZN5CNodeD1Ev':
E:/EclipseWorkspace/Arctic/Debug/../src/CNode.cpp:13: multiple definition of `CNode::~CNode()'
src\Main.o:E:/EclipseWorkspace/Arctic/Debug/../src/Main.cpp:13: first defined here
src\CNode.o: In function `ZN5CNodeD0Ev':
E:/EclipseWorkspace/Arctic/Debug/../src/CNode.cpp:13: multiple definition of `CNode::~CNode()'
src\Main.o:E:/EclipseWorkspace/Arctic/Debug/../src/Main.cpp:13: first defined here
src\CNode.o: In function `ZN5CNodeC2Ev':
E:/EclipseWorkspace/Arctic/Debug/../src/CNode.cpp:9: multiple definition of `CNode::ulIDCreator'
src\Main.o:E:/EclipseWorkspace/Arctic/Debug/../src/Main.cpp:13: first defined here
collect2: ld returned 1 exit status
Build error occurred, build is stopped
Time consumed: 687 ms. console
很奇怪的問題!懷疑是在不一樣文件中編譯再鏈接在一塊有問題。編譯
因而去掉了CNode.cpp,只剩CNode.h。結果問題消失,function
#ifndef CNODE__
#define CNODE__
class CNode {
public:
CNode(){ulID = ++ulIDCreator;};
virtual ~CNode(){};
static unsigned int ulIDCreator;
unsigned int ulID;
};
unsigned int CNode::ulIDCreator = 0;
#endif
console:
cNode1.ID = 1 cNode2.ID = 2 cNode3.ID = 3