Calling Assembly from C
Learn how to integrate assembly routines into C/C++ projects, passing parameters and receiving return values using calling conventions.
Why C Needs Assembly
Why would you mix C/C++ and Assembly? It might seem old-fashioned, but there are powerful reasons!
- Performance: For critical code sections, hand-optimized assembly can be faster than compiler-generated code.
- Hardware Access: Interact directly with hardware features not exposed by C/C++.
- Specific Instructions: Use special CPU instructions (e.g., for cryptography or multimedia) directly.
- Legacy Code: Integrate with existing assembly routines or operating system components.
It allows you to get the "best of both worlds" – C's high-level structure with assembly's low-level power.
The Calling Contract
When C calls an assembly function, they need to agree on a "contract" for how things work. This contract is called a calling convention.
It defines:
- How arguments are passed (registers or stack).
- Who cleans up the stack after the call.
- Which registers the called function must preserve.
For modern 64-bit Linux/macOS systems, the System V AMD64 ABI is standard. We'll focus on this.