Reputation: 5
From what I understand, the caller and the callee both need to have the same calling convention. Otherwise, the stack might be corrupted.
WinMain
is declared with __stdcall
and calls all the functions I've defined. Does this mean all the functions I define should use the stdcall
calling convention?
I've tried not using __stdcall
and nothing bad happened. I have also seen well-known GUI libraries supporting Windows don't use stdcall
. Why is the stack not corrupting?
Upvotes: 0
Views: 132
Reputation: 595377
WinMain is declared with
__stdcall
and calls all the functions I've defined. Does this mean all the functions I define should use thestdcall
calling convention?
No. Calling conventions are handled on a per-function-call basis, right at the call site. The convention dictates how the caller and callee manage the call stack - how parameters are passed, in what order, who cleans up the stack, etc. As long as the caller and callee agree to use the same calling convention on each individual function call, it is perfectly safe for a stdcall
function to call a function that uses a different convention, like cdecl
, and vice versa. A function's calling convention applies only when:
Outside of that, what a function does internally has nothing to with its own calling convention.
For example, lets say that WinMain()
, a stdcall
function, wants to call a cdecl
function.
It does not matter at all that WinMain()
is itself a stdcall
function. While code execution is inside of WinMain()
, it can do whatever it wants. WinMain()
's stdcall
convention is applied only upon entry and exit of WinMain()
itself. That is the contract WinMain()
has with ITS caller.
What matters is that WinMain()
must follow the rules of cdecl
when setting up the call stack for a cdecl
function that it is about to call into, and cleaning up the call stack when that function returns back to WinMain()
.
The same goes for any function call of any calling convention.
I've tried not using
__stdcall
and nothing bad happened. I have also seen well-known GUI libraries supporting Windows don't usestdcall
. Why is the stack not corrupting?
Because the call stack is being managed correctly at every function call and return, so there is no unbalanced cleanup to corrupt the stack.
Upvotes: 1