2009年7月30日 星期四

undefined reference to XXXX::OO

今天搞了一個下午的GNU C++,最後終於有個結論~~~~累....orz。

寫了個Test.h如下
#ifndef SINGLETONCLASS_H_
#define SINGLETONCLASS_H_
#include
using namespace std;

class Test {
 // the default access right is
 static Test *mInstance;
 static string str;

public:
 static string s1;
 static void fun();

Test();
 virtual ~Test();
};
#endif
其cpp檔如下:
#include "SingletonClass.h"
#include
using namespace std;

// Test *Test::mInstance=new Test;
// string Test::s1=NULL;

Test::Test() {
 // TODO Auto-generated destructor stub
}

Test::~Test() {
 // TODO Auto-generated destructor stub
}

Test::fun(){
 mInstance = new Test();
 cout << mInstance << "\n" << str;
}
當main()在call到fun()時,compiler會抱怨
undefined reference to `Test::str'
undefined reference to `Test::mInstance'
主要是因為這兩個member為static,但沒初值(也不可以直接在header file定義出值,基本上header file只負責宣告)。我想,若是compiler放行的話,當有人直接用Test::str有可能會造成runtime error。解決辦法是,在cpp檔initial在header file宣告的static variable,如上述的cpp內容mark掉的兩行註解,這樣,compiler就不會再該了。

其實說穿了,GNU C++ compiler真的不夠friendly,VC跟JAVA都會自己給class type的global變數初值,但...GNU C++ compiler不會~~~~

吼~~~~~把我寶貴的時間還來!!!!!!

沒有留言:

張貼留言