What are the key factors on using different calling conventions? When does someone know to use specific calling conventions such as __cdecl or __stdcall or __fastcall in different occasions.
Examples would be really apprciated.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Most of the time you don’t need to worry about it. Usually you’ll use
__cdecl, but only because that’s the default in Visual C++. C++ member functions, however, use the__thiscallconvention by default in Visual C++A (rather common) situation where you really have to worry about calling conventions is when you pass callbacks to API functions, like those in the Windows API:
Here, we declare
MyWndProc()as having the__stdcallconvention (CALLBACKis#define‘d as__stdcall). This is needed because the operating system expects thatlpfnWndProcpoints to aWNDPROC, which uses theCALLBACKconvention.Just about every Windows API function that accepts a callback requires the callback functions to use the
__stdcallconvention, and since__cdeclis usually the default, you must make this explicit (you would useCALLBACKfor window procedures).This is extremely important because stack corruption can occur if the operating system attempts to call a non-
__stdcallfunction. Unfortunately enough people get this wrong that Windows will actually check for calling convention mismatch specifically for window procedures.While
__stdcallis required for callback functions passed to WinAPI functions, functions that accept a variable number of arguments must use the__cdeclcalling convention, because only the caller will know how to properly pop the variable number of arguments off the stack. Since__cdeclis usually the default, you don’t need to explicitly specify__cdeclfor functions that accept a variable number of arguments.I personally haven’t found a use for
__fastcall, although I’m sure someone has.__clrcallis relevant only if you’re interacting with managed code.