不回答问题,而是举一个编译时优化的例子。当被要求这样做时,gcc 会优化代码。 -O(优化)选项可以在不同级别进行优化。它可以用作-O1、-O2 和-O3。 gcc 手册页准确地描述了每个级别的含义。
-S 选项将 C 转换为汇编并保存在 .s 文件中。
test.c
#include <stdio.h>
int abc;//Global variable
void main()
{
abc = 3;
if(abc == 3)
printf("abc will be always 3");
else
printf("This will never executed");
}
没有 gcc 优化两个字符串出现在汇编代码上。
$ gcc -S test.c;cat test.s
.file "test.c"
.comm abc,4,4
.section .rodata
.LC0:
.string "abc will be always 3"
.LC1:
.string "This will never executed"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $3, abc(%rip)
movl abc(%rip), %eax
cmpl $3, %eax
jne .L2
movl $.LC0, %eax
movq %rax, %rdi
movl $0, %eax
call printf
jmp .L1
.L2:
movl $.LC1, %eax
movq %rax, %rdi
movl $0, %eax
call printf
.L1:
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 4.6.1 20110908 (Red Hat 4.6.1-9)"
.section .note.GNU-stack,"",@progbits
Whit gcc level 1 optimization 只有一个字符串被翻译成汇编
$ gcc -O1 -S test.c;cat test.s
.file "test.c"
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "abc will be always 3"
.text
.globl main
.type main, @function
main:
.LFB11:
.cfi_startproc
subq $8, %rsp
.cfi_def_cfa_offset 16
movl $3, abc(%rip)
movl $.LC0, %edi
movl $0, %eax
call printf
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE11:
.size main, .-main
.comm abc,4,4
.ident "GCC: (GNU) 4.6.1 20110908 (Red Hat 4.6.1-9)"
.section .note.GNU-stack,"",@progbits