I want to enable optimization in g++ without command line parameter.
I know GCC can do it by writing #pragma GCC optimize (2)
in my code.
But it seems won't work in G++.
This page may help: http://gcc.gnu.org/onlinedocs/gcc/Function-Specific-Option-Pragmas.html
My compiler version:
$ g++ --version
g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
<suppressed copyright message>
$ gcc --version
gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
<suppressed copyright message>
I worte some code like this:
#pragma GCC optimize (2)
int main(){
long x;
x=11;
x+=12;
x*=13;
x/=14;
return 0;
}
And compiled it with GCC Not G++. Then I used objdump, which output
08048300 <main>:
8048300: 55 push %ebp
8048301: 31 c0 xor %eax,%eax
8048303: 89 e5 mov %esp,%ebp
8048305: 5d pop %ebp
8048306: c3 ret
8048307: 90 nop
When I removed #param GCC optimize(2)
. objdump output:
080483b4 <main>:
80483b4: 55 push %ebp
80483b5: 89 e5 mov %esp,%ebp
80483b7: 83 ec 10 sub $0x10,%esp
80483ba: c7 45 fc 0b 00 00 00 movl $0xb,-0x4(%ebp)
80483c1: 83 45 fc 0c addl $0xc,-0x4(%ebp)
80483c5: 8b 55 fc mov -0x4(%ebp),%edx
80483c8: 89 d0 mov %edx,%eax
80483ca: 01 c0 add %eax,%eax
80483cc: 01 d0 add %edx,%eax
80483ce: c1 e0 02 shl $0x2,%eax
80483d1: 01 d0 add %edx,%eax
80483d3: 89 45 fc mov %eax,-0x4(%ebp)
80483d6: 8b 4d fc mov -0x4(%ebp),%ecx
80483d9: ba 93 24 49 92 mov $0x92492493,%edx
80483de: 89 c8 mov %ecx,%eax
80483e0: f7 ea imul %edx
80483e2: 8d 04 0a lea (%edx,%ecx,1),%eax
80483e5: 89 c2 mov %eax,%edx
80483e7: c1 fa 03 sar $0x3,%edx
80483ea: 89 c8 mov %ecx,%eax
80483ec: c1 f8 1f sar $0x1f,%eax
80483ef: 89 d1 mov %edx,%ecx
80483f1: 29 c1 sub %eax,%ecx
80483f3: 89 c8 mov %ecx,%eax
80483f5: 89 45 fc mov %eax,-0x4(%ebp)
80483f8: b8 00 00 00 00 mov $0x0,%eax
80483fd: c9 leave
80483fe: c3 ret
80483ff: 90 nop
However, it won't work with G++!
This appears to be a bug in g++
(Bug 48026, references another related issue.)
As a workaround, you can mark each function with __attribute__((optimize("whatever")))
. Not great.
int main() __attribute__((optimize("-O2")));
int main()
{
long x;
x=11;
x+=12;
x*=13;
x/=14;
return 0;
}
$ g++ -Wall -c t.c
$ objdump -d t.o
t.o: file format elf64-x86-64
Disassembly of section .text.startup:
0000000000000000 <main>:
0: 55 push %rbp
1: 31 c0 xor %eax,%eax
3: 48 89 e5 mov %rsp,%rbp
6: 5d pop %rbp
7: c3 retq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With