> On Dec 22, 2014, at 5:59 PM, Jonathan Wakely <jwakely.gcc@xxxxxxxxx> wrote: > >> Shouldn’t it be optimized to: >> >> 0x0000000000400530 <+0>: mov $0x2,%eax >> 0x0000000000400535 <+5>: retq >> >> just like I compiled it with "gcc -O2 t.c”? > > When you compile the whole file with -O2 you also compile main() with > -O2, which is not the same as just optimising one function. Even if I take out the main function, using __attribute__((optimize(“O2”))) is still not the same as -O2. See the following output. $ cat t.c int foo() { return 2; } $ gcc -c -O2 t.c $ gdb t.o (gdb) disas foo Dump of assembler code for function foo: 0x0000000000000000 <+0>: mov $0x2,%eax <==== this is compiled with -O2 0x0000000000000005 <+5>: retq End of assembler dump. $ gcc -c t.c $ gdb t.o (gdb) disas foo Dump of assembler code for function foo: 0x0000000000000000 <+0>: push %rbp <==== this is compiled with no optimization 0x0000000000000001 <+1>: mov %rsp,%rbp 0x0000000000000004 <+4>: mov $0x2,%eax 0x0000000000000009 <+9>: pop %rbp 0x000000000000000a <+10>: retq End of assembler dump. $ cat t.c int foo() __attribute__((optimize("O2"))); <==== Adding the __attribute__ int foo() { return 2; } $ gcc -c t.c $ gdb t.o (gdb) disas foo Dump of assembler code for function foo: 0x0000000000000000 <+0>: push %rbp <==== output is the same as compiled with no optimization 0x0000000000000001 <+1>: mov $0x2,%eax 0x0000000000000006 <+6>: mov %rsp,%rbp 0x0000000000000009 <+9>: pop %rbp 0x000000000000000a <+10>: retq End of assembler dump. > But I believe unless you use some -Ox option on the command line the > optimize attribute has no effect (which is true for optimization > options like -finline-functions). You have to enable optimization in > the first place before you can control the optimization level. I don’t this this is true, at least not true for -fomit-frame-pointer. I've tested __attribute__((optimize(“-fomit-frame-pointer”))), which works regardless optimization is turned on or not. Thanks, Chaoran