Pitfall of "Unicode in Mingw32"
Mingw32 (version 3.15) does not fully support Unicode. There are a few all-too-common pitfalls.
wWinMain
shall not be used
// NG:
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
//...
// OK:
int main(int argc, char** argv)
{
//...
On Mingw32, wWinMain
function is not supported. wmain
function is also not supported. So, the entry function must be main
function in Unicode.
In addition, _tWinMain
and _tmain
function are only available in Multibyte (not Unicode.) These are mapped to WinMain
and main
in Multibyte.
How to get hInstance
from main function?
HINSTANCE hInstance;
hInstance = GetModuleHandle(NULL);
Note that hPrevInstance
of wWinMain
arguments is always NULL
on Win32.
How to get lpCmdLine
from main function?
Use GetCommandLine()
function. Unlike lpCmdLine
, the return value of GetCommandLine()
is entire command line, including the program name.
__wargv
shall not be used
// NG:
for (i = 0; i < __argc; i++) {
arg = __wargv[i];
//...
}
// OK:
INT argc;
WCHAR **argv;
wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (i = 0; i < argc; i++) {
arg = wargv[i];
//...
}
LocalFree(wargv);
__wargv
is also not supported. To get argument list, use CommandLineToArgvW
and GetCommandLineW
function. Note that CommandLineToArgvA
is not defined on win32api.
My solution of above pitfalls
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
// ...
}
#ifdef _UNICODE
#ifndef _tWinMain // Mingw32 does not implement wide startup module
int main(int argc, char **argv)
{
HINSTANCE hInstance = GetModuleHandle(NULL);
int retval = 0;
retval = _tWinMain(hInstance, NULL, _T("") /* lpCmdLine is not available*/, SW_SHOW);
return retval;
}
#endif
#endif /* _UNICODE */