__stdcall

ccalling-conventionstdcallwinapi

I'm learning about Win32 programming, and the WinMain prototype looks like:

int WINAPI WinMain ( HINSTANCE instance, HINSTANCE prev_instance, PSTR cmd_line, int cmd_show )

I was confused as to what this WINAPI identifier was for and found:

#define WINAPI      __stdcall

What does this do? I'm confused by this having something at all after a return type. What is __stdcall for? What does it mean when there is something between the return type and function name?

Best Answer

__stdcall is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.

There are a number of other calling conventions, __cdecl, __thiscall, __fastcall and the wonderfully named __declspec(naked). __stdcall is the standard calling convention for Win32 system calls.

Wikipedia covers the details.

It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain). If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.