Search code examples
winapiunicodelinkerwinmain

What is the correct way to define a UNICODE independent WinMain function?


What is the correct way to define a UNICODE independent WinMain function for a Windows program that uses the CRT?

I am inclined to think that it should be something like

WINAPI
#ifdef UNICODE
  wWinMain
#else
  WinMain
#endif
 ( ... ) {
  ...
}

However, I am wondering if there is not already a predefined macro that expands to the correct symbol when compiling the source units (like those that are offered in the windows header files that expand to either WinApiFuncA or WinApiFuncW.


Solution

  • In <tchar.h>, the macro _tWinMain expands to WinMain or wWinMain depending on project settings. This isn't enough, though; you need to declare the third argument (lpCmdLine) with the charset-agnostic LPTSTR too:

    int APIENTRY _tWinMain(
        HINSTANCE hInstance, 
        HINSTANCE hPrevInstance, 
        LPTSTR lpCmdLine, 
        int nShowCmd
    )
    

    If Unicode is enabled on the project, this becomes LPWSTR, giving the signature:

    int APIENTRY wWinMain(
        HINSTANCE hInstance, 
        HINSTANCE hPrevInstance, 
        LPWSTR lpCmdLine, 
        int nShowCmd
    )
    

    If Unicode is not enabled, you get the signature:

    int APIENTRY WinMain(
        HINSTANCE hInstance, 
        HINSTANCE hPrevInstance, 
        LPSTR lpCmdLine, 
        int nShowCmd
    )