(我一直沒能找到任何類似的問題......所以,我希望你能幫助我)在提領靜態變量
在C++中的程序,我開發鏈接錯誤,我有一個類模擬一個線程。我會在這裏稱它爲「測試」。其中,我有一個靜態地圖(來自STL的std::map
),其中存儲了一些信號量(因爲我需要所有線程才能訪問相同的信號量)。 (我認爲這是不值得解釋爲什麼我用,而不是一個vector
一個map
,但我認爲這不應該是一個問題)
「獲取」這個靜態變量,我創建了一個getMutexHash()
功能,它返回一個指向靜態的指針map
。但是,出於某種原因,在編譯之後,我在嘗試返回this pointer
時遇到鏈接器錯誤。
下面的代碼舉例說明了問題:
// MAIN.CPP
#include "Test.h"
int main()
{
Test test;
map<int, pthread_mutex_t>* mutexHash = test.getMutexHash();
return 0;
}
// TEST.H
#include <map>
#include <pthread.h>
using namespace std;
class Test
{
public:
map<int, pthread_mutex_t>* getMutexHash();
private:
static map<int, pthread_mutex_t> mutexHash;
};
// TEST.CPP
#include "Test.h"
map<int, pthread_mutex_t>* Test::getMutexHash()
{
return &mutexHash;
}
編譯時,我沒有得到任何錯誤,也沒有警告;但鏈接時,我收到此錯誤:
Test.o: In function `Test::getMutexHash()':
Test.cpp:(.text+0x9): undefined reference to `Test::mutexHash'
collect2: ld returned 1 exit status
有人可以幫助我嗎?
可能重複http://stackoverflow.com/questions/8380289/undefined-reference-to-a-靜態成員的類) –