okay, i’m a bit befuddled with this error. What i’m trying to do here is make a basic_string that will be either char or wchar_t when UNICODE and _UNICODE are defined (this is in WINAPI). This does work, but for some reason, i’m unable to define a function that receives a std::basic_string outside the class where it’s declared. Here’s an example:
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);
}
This yields a link error, claiming the test::func was never defined. However, if i just define inside the class like this:
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
it works fine. However, i really like to keep my declarations and definitions in separate files to avoid redefinition errors and for organization. Here’s the kicker though. when i have func defined in test.cpp like before and don’t define UNICODE and _UNICODE in my main.cpp, i don’t get the link errors. So really, the only time i get a link error is when TCHAR becomes a wchar_t. So here’s my main and the error real quick…
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:
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
Anyone have a clue what’s going on and how i might go about fixing this?
I think because you are putting
#define UNICODEinmain.cpp, the other part doesn’t know about this. Whentest.cppis compiled,UNICODEis not defined. You can try putting theUNICODEdefinition as project processor macro. Or intest.h, write#define UNICODEand#define _UNICODEbefore including Windows.h .On another note, because you’ve included Windows.h in Test.h, you should not include it again in main.cpp .
Consider create a default project in visual studio, and use
Precompiled Headers. This way, put such include in stdafx.h will address all your problems: