Cover Image for Calling Conventions in C++
115 views

Calling Conventions in C++

The C++ calling convention defines the rules for how functions are called and how their parameters are passed between the caller (the code that invokes the function) and the callee (the function being called). Different platforms and compilers may have different calling conventions. Common calling conventions in C++ include:

  1. C Calling Convention (cdecl): This is the default calling convention in C and C++. In cdecl, parameters are pushed onto the stack in reverse order (right to left), and the caller is responsible for cleaning up the stack after the call. Function names are not decorated, making it suitable for calling C functions from C++ and vice versa.
  2. Standard Calling Convention (stdcall): In stdcall, parameters are pushed onto the stack in a specific order (left to right), and the callee is responsible for cleaning up the stack. This calling convention is often used in the Windows API.
  3. Fastcall Calling Convention: Fastcall is an optimization where some of the function’s parameters are passed in registers rather than on the stack. It is typically used to optimize frequently called functions.
  4. Thiscall Calling Convention: Thiscall is specific to member functions of C++ classes. In this convention, the this pointer is passed in a register or as an implicit first parameter. It is commonly used in Microsoft Visual C++.
  5. Vectorcall Calling Convention: Vectorcall is another Windows-specific calling convention designed for optimizing vectorized code.
  6. Linux/Unix Calling Conventions: On Linux and Unix-based systems, the calling convention often follows a combination of cdecl and system-specific conventions.
  7. ARM Calling Conventions: ARM-based processors have their own calling conventions, including the ARM AAPCS (ARM Procedure Call Standard) and ARM64 AAPCS64 for 64-bit ARM.
  8. x86_64 Calling Convention: For 64-bit x86 (x86_64) processors, there’s a specific calling convention that involves using registers for parameter passing.

The choice of calling convention can affect function compatibility between different libraries and code modules. It’s important to be aware of the calling convention used by the functions you call, especially when working with libraries, system calls, and foreign function interfaces (FFI).

In practice, most of the time, you don’t need to worry about calling conventions, as the compiler and platform take care of the details. However, when interfacing with low-level code or external libraries, understanding the calling convention is crucial for ensuring proper function calls and avoiding compatibility issues.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS