- 第一章 CPU 简介
- 第二章 Hello,world!
- 第三章 函数开始和结束
- 第四章 栈
- Chapter 5 printf() 与参数处理
- Chapter 6 scanf()
- CHAPER7 访问传递参数
- Chapter 8 一个或者多个字的返回值
- Chapter 9 指针
- Chapter 10 条件跳转
- 第 11 章 选择结构 switch()/case/default
- 第 12 章 循环结构
- 第 13 章 strlen()
- Chapter 14 Division by 9
- chapter 15 用 FPU 工作
- Chapter 16 数组
- Chapter 17 位域
- 第 18 章 结构体
- 19 章 联合体
- 第二十章 函数指针
- 第 21 章 在 32 位环境中的 64 位值
- 第二十二章 SIMD
- 23 章 64 位化
- 24 章 使用 x64 下的 SIMD 来处理浮点数
- 25 章 温度转换
- 26 章 C99 的限制
- 27 章 内联函数
- 第 28 章 得到不正确反汇编结果
- 第 29 章 花指令
- 第 30 章 16 位 Windows
- 第 31 章 类
- 三十二 ostream
- 34.2.2 MSVC
- 34.2.3 C++ 11 std::forward_list
- 34.3 std::vector
- 34.4 std::map and std::set
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
27 章 内联函数
内联代码是指当编译的时候,将函数体直接嵌入正确位置,而不是在这个位置放上函数声明。
#!cpp
#include <stdio.h>
int celsius_to_fahrenheit (int celsius)
{
return celsius * 9 / 5 + 32;
};
int main(int argc, char *argv[])
{
int celsius=atol(argv[1]);
printf ("%d\n", celsius_to_fahrenheit (celsius));
};
这个编译是意料之中的,但是如果换成 GCC 的优化方案,我们会看到:
清单 27.2: GCC 4.8.1 -O3
#!bash
_main:
push ebp
mov ebp, esp
and esp, -16
sub esp, 16
call ___main
mov eax, DWORD PTR [ebp+12]
mov eax, DWORD PTR [eax+4]
mov DWORD PTR [esp], eax
call _atol
mov edx, 1717986919
mov DWORD PTR [esp], OFFSET FLAT:LC2 ; "%d\12\0"
lea ecx, [eax+eax*8]
mov eax, ecx
imul edx
sar ecx, 31
sar edx
sub edx, ecx
add edx, 32
mov DWORD PTR [esp+4], edx
call _printf
leave
ret
这里的除法由乘法完成。 是的,我们的小函数被放到了 printf() 调用之前。为什么?因为这比直接执行函数之前的“调用/返回”过程速度更快。 在过去,这样的函数在函数声明的时候必须被标记为“内联”。在现代,这样的函数会自动被编译器识别。 另外一个普通的自动优化的例子是内联字符串函数,比如 strcpy(),strcmp() 等
清单 27.3 : 另一个简单的例子
#!cpp
bool is_bool (char *s)
{
if (strcmp (s, "true")==0)
return true;
if (strcmp (s, "false")==0)
return false;
assert(0);
};
清单 27.4: GCC 4.8.1 -O3
#!bash
_is_bool:
push edi
mov ecx, 5
push esi
mov edi, OFFSET FLAT:LC0 ; "true\0"
sub esp, 20
mov esi, DWORD PTR [esp+32]
repz cmpsb
je L3
mov esi, DWORD PTR [esp+32]
mov ecx, 6
mov edi, OFFSET FLAT:LC1 ; "false\0"
repz cmpsb
seta cl
setb dl
xor eax, eax
cmp cl, dl
jne L8
add esp, 20
pop esi
pop edi
ret
这是一个经常可以见到的关于 MSVC 生成的 strcmp() 的例子。
清单 27.5: MSVC
#!bash
mov dl, [eax]
cmp dl, [ecx]
jnz short loc_10027FA0
test dl, dl
jz short loc_10027F9C
mov dl, [eax+1]
cmp dl, [ecx+1]
jnz short loc_10027FA0
add eax, 2
add ecx, 2
test dl, dl
jnz short loc_10027F80
loc_10027F9C: ; CODE XREF: f1+448
xor eax, eax
jmp short loc_10027FA5
; ---------------------------------------------------------------------------
loc_10027FA0: ; CODE XREF: f1+444
; f1+450
sbb eax, eax
sbb eax, 0FFFFFFFFh
我写了一个小的用于搜索和归纳的 IDA 脚本,这样的脚本经常能在内联代码中看到: https://github.com/yurichev/IDA_scripts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论