Understanding the Variety of Calling Conventions in C/C
C/C provides a range of calling conventions, each with distinct characteristics and implications for function calls. These conventions determine how arguments are passed to functions and how return values are handled.
Available Calling Conventions
The primary calling conventions available in C/C are:
-
cdecl: Arguments are pushed onto the stack right-to-left, with callee-saved registers (EAX, ECX, EDX) and caller-saved registers (stack pointer and the rest).
-
syscall: Similar to cdecl, but with EAX, ECX, and EDX not preserved. Parameter list size is passed in AL.
-
pascal: Arguments are pushed onto the stack left-to-right, and the callee is responsible for stack balancing.
-
stdcall: A variation of pascal where the callee is responsible for stack cleanup but parameters are pushed onto the stack right-to-left. EAX, ECX, and EDX are designated for use within the function.
-
fastcall: Passes the first two arguments into ECX and EDX registers, and remaining arguments onto the stack right-to-left.
Extended Calling Conventions
In addition to these standard conventions, there are specialized variants:
-
vectorcall: Pass vector arguments using SIMD registers, extending support for passing homogeneous vector aggregate values.
-
safecall: Encapsulates COM error handling, with exceptions passed back as HResult in EAX and results passed by reference on the stack.
-
Microsoft X64 Calling Convention: Uses specific registers for integer and floating-point arguments, with additional arguments pushed onto the stack. The caller is responsible for allocating "shadow space" on the stack.
Choosing the Right Convention
The appropriate calling convention depends on the specific platform, compiler, and application requirements. Consider factors such as parameter count, register usage, and performance optimizations when selecting a calling convention.
For example, stdcall is commonly used to call Windows API functions, while cdecl is often used in Unix-like environments. fastcall may offer faster performance for functions with few parameters.
Additional Resources
- [Microsoft Docs: Calling Conventions](https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention)
- [Wikipedia: Calling Conventions](https://en.wikipedia.org/wiki/Calling_convention)
The above is the detailed content of How Do Different Calling Conventions Impact Function Calls in C/C ?. For more information, please follow other related articles on the PHP Chinese website!