2012-04-07 9 views
1

好吧,我對這個錯誤有點困惑。我在這裏要做的是做一個basic_string,當UNICODE和_UNICODE被定義時(這是在WINAPI中)將是char或wchar_t。這確實有效,但出於某種原因,我無法定義一個函數,它在聲明它的類之外接收std :: basic_string。這裏有一個例子:basic_string <TCHAR>不允許在聲明的地方之外定義

test.h

#ifndef TEST_H 
#define TEST_H 

#include <Windows.h> 
#include <string> 

class Test 
{ 
public: 
    void func(std::basic_string<TCHAR> stringInput); 
}; 

#endif 

TEST.CPP

#include "test.h" 

void Test::func(std::basic_string<TCHAR> stringInput) 
{ 
    MessageBox(NULL, stringInput.c_str(), TEXT("It works!"), MB_OK); 
} 

這將產生一個鏈接錯誤,聲稱測試::從未定義FUNC。但是,如果我只是這樣定義類中:

test.h

#ifndef TEST_H 
#define TEST_H 

#include <Windows.h> 
#include <string> 

class Test 
{ 
public: 
    void func(std::basic_string<TCHAR> stringInput) 
    { 
     MessageBox(NULL, stringInput.c_str(), TEXT("It works!"), MB_OK); 
    } 
} 

#endif 

它工作正常。但是,我真的很想將我的聲明和定義保存在單獨的文件中,以避免重新定義錯誤和組織。儘管這是踢球。當我有像以前一樣在test.cpp中定義的func,並且不在我的main.cpp中定義UNICODE和_UNICODE時,我不會收到鏈接錯誤。所以真的,唯一一次我得到一個鏈接錯誤是當TCHAR變成wchar_t。因此,這裏是我的主,誤差真正的快...

的main.cpp

#define UNICODE  // this won't compile when these are defined 
#define _UNICODE 

#include <Windows.h> 
#include <string> 

#include "test.h" 

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow) 
{ 
    Test test; 
    test.func(TEXT("wakka wakka")); 
    return 0; 
} 

錯誤:

error LNK2019: unresolved external symbol "public: void __thiscall Test::func(class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> >)" ([email protected]@@[email protected][email protected][email protected]@@[email protected][email protected]@@[email protected]@@Z) referenced in function [email protected]

任何人都有一個線索是怎麼回事,如何我可能會去修復這個?

+0

你實際上是否* *所有*你的目標文件鏈接在一起? – 2012-04-07 23:57:29

回答

4

我想因爲你把#define UNICODE放在main.cpp,另一部分不知道這個。當編譯test.cpp時,UNICODE未定義。您可以嘗試將UNICODE定義作爲項目處理器宏。或者在test.h之前,在包含Windows.h之前寫入#define UNICODE#define _UNICODE

另一方面,因爲你在Test.h中包含了Windows.h,所以你不應該再在main.cpp中包含它。

請考慮在visual studio中創建一個默認項目,並使用Precompiled Headers。這樣,把這樣的包括在stdafx.h將解決您所有的問題:

#define UNICODE 
#include <windows.h> 
#include <string> 
+0

Windows.h在它的頂部也有一個#ifndef #define,所以它永遠不會真正包含多次。我傾向於將依賴關係保持在最低限度,因此,如果在包含test.h之前沒有包含Windows,那麼它將正確編譯。 ANNNyway,在test.h中定義它確實解決了這個問題。我只是好奇爲什麼編譯器可以在test.h中看到它,而不是在我的main.cpp中。 .cpp文件是在頭文件之前編譯的?另外,我從來沒有真正理解預編譯頭文件,你可能有教程嗎? – FatalCatharsis 2012-04-08 01:30:50

+1

當然Windows.h有定義來防止被包含兩次。但不是所有的頭都有。編譯器在性能和組織方面都很差,不止一次包含同一個文件。在您的原始代碼中,只有main.cpp會看到「UNICODE」。所以main.cpp知道''TCHAR''是''wchar_t''。但是,當編譯test.cpp時,它不會看到這一點,因此測試。cpp是在「TCHAR」等於「char」的基礎上編譯的。 – 2012-04-08 01:36:48

+1

試試谷歌解釋預編譯頭。這裏有幾個鏈接:http://en.wikipedia.org/wiki/Precompiled_header,http://msdn.microsoft.com/en-us/library/szfdksca(v=vs.71).aspx,http:// gameswithwithin.com/the-care-and-feeding-of-pre-compiled-headers。 – 2012-04-08 01:39:06

相關問題