这样的事情:
static void MyFunction(int x, int y) {};
Clalen会在被叫时将它们优化掉吗?
答案 0 :(得分:2)
这取决于优化级别。如果您没有优化,那么you'll probably still end up with a function。但是,即使使用-O
you'll see it disappear也是如此。如果你的函数没有被标记为static
,那么它会有点复杂,因为其他翻译单元需要存在这个函数,所以你可能see an empty body,并且对它的调用在同一个TU中被省略了,但功能本身必须存在。
答案 1 :(得分:1)
当然,只要定义对于调用站点的编译器是可见的。既然你已声明它static
可能总是如此。
答案 2 :(得分:0)
当然是-O3(实际上是任何!= 0)
答案 3 :(得分:0)
鉴于代码:
/* Optmizing empty functions */
static void myFunc(int x, int y);
int main(void)
{
int x=1, y=2;
myFunc(x, y);
return 0;
}
static void myFunc(int x, int y)
{
;
}
每个优化级别生成的程序集如下所示:
gcc emptyfunc.c -g -O0 -o emptyfunc.x
Dump of assembler code for function main:
0x0000000000000660 <+0>: push %rbp
0x0000000000000661 <+1>: mov %rsp,%rbp
0x0000000000000664 <+4>: sub $0x10,%rsp
0x0000000000000668 <+8>: movl $0x1,-0x4(%rbp)
0x000000000000066f <+15>: movl $0x2,-0x8(%rbp)
0x0000000000000676 <+22>: mov -0x8(%rbp),%edx
0x0000000000000679 <+25>: mov -0x4(%rbp),%eax
0x000000000000067c <+28>: mov %edx,%esi
0x000000000000067e <+30>: mov %eax,%edi
0x0000000000000680 <+32>: callq 0x68c <myFunc>
0x0000000000000685 <+37>: mov $0x0,%eax
0x000000000000068a <+42>: leaveq
0x000000000000068b <+43>: retq
End of assembler dump.
gcc emptyfunc.c -O1 -o emptyfunc-gccO1.x
Dump of assembler code for function main:
0x0000000000000660 <+0>: mov $0x0,%eax
0x0000000000000665 <+5>: retq
End of assembler dump.
gcc emptyfunc.c -Ofast -o emptyfunc-gccOfast.x
Dump of assembler code for function main:
0x0000000000000530 <+0>: xor %eax,%eax
0x0000000000000532 <+2>: retq
End of assembler dump.
clang emptyfunc.c -o emptyfunc-clangO0.x -g -O0
Dump of assembler code for function main:
0x00000000004004c0 <+0>: push %rbp
0x00000000004004c1 <+1>: mov %rsp,%rbp
0x00000000004004c4 <+4>: sub $0x10,%rsp
0x00000000004004c8 <+8>: movl $0x0,-0x4(%rbp)
0x00000000004004cf <+15>: movl $0x1,-0x8(%rbp)
0x00000000004004d6 <+22>: movl $0x2,-0xc(%rbp)
0x00000000004004dd <+29>: mov -0x8(%rbp),%edi
0x00000000004004e0 <+32>: mov -0xc(%rbp),%esi
0x00000000004004e3 <+35>: callq 0x4004f0 <myFunc>
0x00000000004004e8 <+40>: xor %eax,%eax
0x00000000004004ea <+42>: add $0x10,%rsp
0x00000000004004ee <+46>: pop %rbp
0x00000000004004ef <+47>: retq
End of assembler dump.
clang emptyfunc.c -o emptyfunc-clangOz.x -Oz
Dump of assembler code for function main:
0x00000000004004c0 <+0>: xor %eax,%eax
0x00000000004004c2 <+2>: retq
End of assembler dump.
正如你所看到的,是的,它当然会删除空函数。