GCC Optimization Flags

2.9k Views Asked by At

I'm trying to get together a bunch of executables that have different optimizations run on them. My only question is, should gcc commands with -c also be able to use -O flags as well? I ask this, because I realize when I only place the optimization flag in the gcc command to make the exe, the sizes do not differ between files at all, which doesn't seem right.

For example, I have something like this:

g++ -c cat.cpp 
g++ -c dog.cpp        
g++ cat.o dog.o -o catdog

Would I use the flags on everything like this:

g++ -c -O2 sobol.cpp
g++ -c -O2 sobol_prb.cpp        
g++ sobol.o sobol_prb.o -O2 -o catdog02

If anyone could help me out, I'd greatly appreciate it.

Thank you.

3

There are 3 best solutions below

0
On

You can do it like this:

  g++ sobol.cpp sobol_prb.cpp -O2 -o catdog02

If you need to compile more than 2 or three files, you should consider a Makefile.

If you're working on a non-trivial project, you should start thinking about a build system as @polkadotcadaver suggested, though l'd go with either automake or cmake, as they're more popular than other build systems.

0
On

Yes, use the optimisation flags on every object compilation.

(In general, use a build system like SCons which makes this kind of thing easier, even if it's a 'small' project.)

0
On

When you execute gcc on object (.o) files, this basically just calls the linker with appropriate libraries selected and so on. In the usual mode this step involves no compilation and the optimization flags will have no effect.

Optimization happens in compilation step (the one with .cpp inputs) and that's where optimization switches are relevant.

The story is a bit different with link time optimization (-flto), where you need to use optimization switches when compiling and linking.