Optimization and flags for making a static library with g++

旧城冷巷雨未停 提交于 2019-12-02 14:10:38

The rule of thumb:

When you need to debug, use -O0 (and -g to generate debugging symbols.)

When you are preparing to ship it, use -O2.

When you use gentoo, use -O3...!

When you need to put it on an embedded system, use -Os (optimize for size, not for efficiency.)

The gcc manual list all implied options by every optimization level. At O2, you get things like constant folding, branch prediction and co, which can change significantly the speed of your application, depending on your code. The exact options are version dependent, but they are documented in great detail.

To build a static library, you use ar as follows:

ar rc libfoo.a foo.o foo2.o ....
ranlib libfoo.a

Ranlib is not always necessary, but there is no reason for not using it.

Regarding when to use what optimization option - there is no single correct answer.

Certain optimization levels may, at times, decrease performance. It depends on the kind of code you are writing and the execution pattern it has, and depends on the specific CPU you are running on.

(To give a simple canonical example - the compiler may decide to use an optimization that makes your code slightly larger than before. This may cause a certain part of the code to no longer fit into the instruction cache, at which point many more accesses to memory would be required - in a loop, for example).

It is best to measure and optimize for whatever you need. Try, measure and decide.

One important rule of thumb - the more optimizations are performed on your code, the harder it is to debug it using a debugger (or read its disassembly), because the C/C++ source view gets further away from the generated binary. It is a good rule of thumb to work with fewer optimizations when developing / debugging for this reason.

There are many optimizations that a compiler can perform, other than loop unrolling and inlining. Loop unrolling and inlining are specifically mentioned there since, although they make the code faster, they also make it larger.

To make a static library, use 'g++ -c' to generate the .o files and 'ar' to archive them into a library.

badPhysicist

In regards to the Static library question the answer given by David Cournapeau is correct but you can alternatively use the 's' flag with 'ar' rather than running ranlib on your static library file. The 'ar' manual page states that

Running ar s on an archive is equivalent to running ranlib on it.

Whichever method you use is just a matter of personal preference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!