Home > Mobile >  Invalid conversion from 'int' to 'LPCSTR' in a basic Win32 API app
Invalid conversion from 'int' to 'LPCSTR' in a basic Win32 API app

Time:11-21

I have started learning the Win32 API recently with successful compilations every time until now.

I added an icon to the resource files (main.rc and resource.h), and after including the main.h header file (where the resource header is referenced), I got the following conversion error:

Error: invalid conversion from 'int' to 'LPCSTR' {aka 'const char*'} [-f permissive]

note: in definition of macro 'IDI_MYICON'

I looked at some solutions online, however most if not all were about non-Unicode strings, not resources. Did I forget anything?

main.c file:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG msg;

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = 0;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hIcon = LoadIcon(NULL, IDI_MYICON); //icon resource referenced here
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW   1);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = g_szClassName;
    wc.hIconSm = LoadIcon(NULL, IDI_MYICON); //icon resource referenced here as well
//.....

main.rc file:

#include "resource.h"

IDI_MYICON ICON "my_icon.ico"

main.h file:

#pragma once

#include "resource.h"

resource.h file:

#define IDI_MYICON 101

CodePudding user response:

API functions like LoadCursor and LoadIcon take a pointer to a string as the parameter to specify the resource to load, not an integer (which is what IDI_MYICON is).

The reason for this is that resources can have names as identifiers, not just numeric identifiers.

To use a numeric identifier with these APIs you need to cast it as a string pointer. The API provides the MAKEINTRESOURCE macro for this purpose.

For example, wc.hIconSm = LoadIcon(NULL, MAKEINTRESOURCE(IDI_MYICON));.

  • Related