basic_string <tchar>不允许在声明它的地方之外进行定义</tchar>

时间:2012-04-07 23:32:27

标签: c++ winapi

好吧,我有点迷惑这个错误。我在这里尝试做的是创建一个basic_string,当定义UNICODE和_UNICODE时,它将是char或wchar_t(这是在WINAPI中)。这确实有效,但由于某种原因,我无法定义一个在声明它的类之外接收std :: basic_string的函数。这是一个例子:

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);
}

这会产生链接错误,声称从未定义test :: 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> >)" (?func@Test@@QAEXV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@@Z) referenced in function _WinMain@16

任何人都知道发生了什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分: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>