C++ 是一门"贴近硬件"的语言。它不仅能够无缝调用 C 语言代码,还能与汇编语言直接交互。这种能力使得 C++ 成为系统编程、嵌入式开发、性能优化领域的首选语言。
让我们探索 C++、C 语言与汇编之间的协同之道。
C++ 与 C 的血脉联系
C++ 起源于 C 语言,因此两者有着天然的兼容性。但直接混用时需要注意一些细节。
extern "C" 的作用
C++ 编译器会对函数名进行"名称修饰"(Name Mangling),以支持函数重载:
// C++ 中的这两个函数voidfoo(intx);voidfoo(doublex);// 编译后可能变成类似这样的名字// _Z3fooi// _Z3food
但 C 语言不支持函数重载,也不会进行名称修饰。为了让 C++ 调用 C 代码(或反过来),需要使用 extern "C":
// 声明一个 C 函数extern"C"voidc_function(int x);// 或者包裹多个声明extern"C"{voidc_func1(intx);voidc_func2(doubley);intc_func3(constchar*str);}// 在 C++ 中定义一个供 C 调用的函数extern"C"intcpp_for_c(int a,int b){return a + b;}
#include <iostream>
int add_asm(int a, int b)
{
__asm
{
mov eax, a
add eax, b
// 返回值自动在 eax 中
}
}
int main()
{
std::cout << "3 + 5 = " << add_asm(3, 5) << std::endl;
return 0;
}
; fast_math.asm (NASM 语法)
section .text
global fast_multiply
; int fast_multiply(int a, int b)
fast_multiply:
mov eax, edi ; 第一个参数 (System V ABI)
imul eax, esi ; 乘以第二个参数
ret
// main.cpp
#include <iostream>
extern "C" int fast_multiply(int a, int b);
int main()
{
std::cout << "7 * 8 = " << fast_multiply(7, 8) << std::endl;
return 0;
}