【发布时间】:2011-12-13 14:09:59
【问题描述】:
有这样的代码:
int fun1(){
return 2 + 3;
}
inline int fun2(){
return 4 + 5;
}
int main(){
int a = fun1();
int b = fun2();
return 0;
}
及对应的汇编代码:
.file "prog47.cpp"
.text
.globl _Z4fun1v
.type _Z4fun1v, @function
_Z4fun1v:
.LFB0:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
pushl %ebp
.cfi_def_cfa_offset 8
movl %esp, %ebp
.cfi_offset 5, -8
.cfi_def_cfa_register 5
movl $5, %eax
popl %ebp
ret
.cfi_endproc
.LFE0:
.size _Z4fun1v, .-_Z4fun1v
.section .text._Z4fun2v,"axG",@progbits,_Z4fun2v,comdat
.weak _Z4fun2v
.type _Z4fun2v, @function
_Z4fun2v:
.LFB1:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
pushl %ebp
.cfi_def_cfa_offset 8
movl %esp, %ebp
.cfi_offset 5, -8
.cfi_def_cfa_register 5
movl $9, %eax
popl %ebp
ret
.cfi_endproc
.LFE1:
.size _Z4fun2v, .-_Z4fun2v
.text
.globl main
.type main, @function
main:
.LFB2:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
pushl %ebp
.cfi_def_cfa_offset 8
movl %esp, %ebp
.cfi_offset 5, -8
.cfi_def_cfa_register 5
andl $-16, %esp
subl $16, %esp
call _Z4fun1v
movl %eax, 12(%esp)
call _Z4fun2v # why fun2 is called?
movl %eax, 8(%esp)
movl $0, %eax
leave
ret
.cfi_endproc
.LFE2:
.size main, .-main
.section .note.GNU-stack,"",@progbits
为什么函数 fun2 没有像普通函数一样被内联和调用?我读过 inline 关键字只是对编译器的提示,它不必内联函数,但是 fun2 的定义非常简单,因此可以内联。如何强制 g++ 内联函数?
【问题讨论】:
-
[您确定需要内联函数吗?还是只是出于兴趣才问这个问题?]
-
所有代码都应该消失,因为它没有有用的副作用。不要忘记启用优化器。
-
开启一些优化并将你的内联函数声明为静态将是一个好的开始。
-
注意函数内联只在-O3模式下有效linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/…
-
@cyco130,好主意。如果总是“静态内联 T f(...)”,它可以改变内联的内容吗?