简体   繁体   中英

Does every function in a Windows GUI application need to use stdcall?

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?

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?

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:

  • the function is being entered by a new caller.
  • the function is returning back to that caller.
  • the function is accessing its own parameters.

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 use stdcall . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM