anathrax
anathrax

Reputation: 101

Win32 API - error: assigning to 'LPCSTR' from incompatible type 'const wchar_t[]'

I have the following code,

#include <windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    // Register the window class.

    WNDCLASS wc = { };

    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = "Sample Window Class";
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;

    RegisterClass(&wc);

    // Create the window.

    HWND hwnd = CreateWindowEx(
        0,                              // Optional window styles.
        wc.lpszClassName,               // Window class
        "Learn to Program Windows",    // Window text
        WS_OVERLAPPEDWINDOW,            // Window style

        // Size and position
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

        NULL,       // Parent window    
        NULL,       // Menu
        hInstance,  // Instance handle
        NULL        // Additional application data
    );

    if (hwnd == NULL)
    {
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);

    // Run the message loop.

    MSG msg = { };
    while (GetMessage(&msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

The error occurs when I try to assign a value of the wrong type 'const char [20]' to 'LPCWSTR' like so:

    wc.lpszClassName = "Sample Window Class";

                       ^~~~~~~~~~~~~~~~~~~~~~

If I prefix a string with L"", the Visual C++ compiler will no longer complain.

On the other hand, if I try to compile the same code with gcc or clang, it works just fine, but after I add the prefix it gives me the following error:

error: assigning to 'LPCSTR' (aka 'const char *') from incompatible type 'const wchar_t[20]'

I wonder what causes this strange behaviour, and how could I make one code compatible for all compilers?

Upvotes: 0

Views: 301

Answers (0)

Related Questions