TCHAR and unresolved external symbol (LNK2019) error in C++ program?
Question
My project has two cpp files and one header file. One cpp file contains the implementation of a single class and its declaration is in the header file. The other cpp file is which contains the int main
function.
One of the constructors of the class includes a TCHAR
parameter and it is cited as the unresolved function in LNK2019
linker error.
I'm using visual studio 2010 and I have set the Character set
option in the project properties to Not Set
so that I can choose between char
and wchar_t
using UNICODE
and _UNICODE
macros.
Currently I have defined these in the beginning of my main cpp file and the header files are included after those two. However, if I define these macros in the beginning of header file, the project compiles perfectly.
Is there anyway to solve this issue ? Or do I have to hard code the class to use either char
or wchar_t
?
Thanks.
La solution
You are getting the linker error because you are defining the UNICODE
/_UNICODE
macros inside of main.cpp but not in your class's implementation .cpp. As such, when main.cpp includes your class's header file, it sees TCHAR
as wchar_t
, but when your implementation .cpp includes your header file, it sees TCHAR
as char
instead. You have a mismatch that causes the linker error because main.cpp calls a wchar_t
constructor that you have not actually implemented.
You are supposed to look for the presence of the UNICODE
/_UNICODE
macros, not actually define them manually. Set the "Character Set" option to MBCS or Unicode so the IDE/compiler can manage the macros globally for the entire project as a whole for you. I don't know what setting it to "Not Set" actually does, but it is not what you actually need in this situation.
Autres conseils
Macros are preprocessor constructs that apparently confuse you. Your code, even if you succeed will confuse others too. The macros UNICODE
and _UNICODE
have to be defined before TCHAR
is defined, defining them before TCHAR
is used is too late. Better leave it to your project settings.
Set the project's Character Set
to Unicode
, that is the character set what Windows uses internally anyway. Then that TCHAR
is wchar_t
and the API call macros Something()
always expand to SomethingW()
. You can use char
and wchar_t
explicitly everywhere and the readers of code will exactly see what is what, no dim and unclear TCHAR
for them.
Windows API functions SomethingA()
are just wrappers around SomethingW()
so using the A versions a lot is inefficient. If you ever need to call API function SomethingA()
, then do it explicitly, so everybody see that you had to do something inefficient.