C compiler flags

A short post about some habits with compiling C.

Keep it simple

This is a well known and good advice for most things involving design and development, and it really can’t be underlined enough as a general advice. Don’t start lining up obscure compiler flags like -fomit-frame-pointer -mfpmath=sse unless you really think you understand and need them, and probably not even then.

Use a C standard (c11)

Aim for reusable, portable, and standardized code, and don’t marry a specific compiler. In particular, if working on a unix platform, allow for both Clang and gcc, and try to avoid relying on specific compilers extensions.

Don’t panic because something like for example strdup is not part of the standard. These specific cases are usually easily worked around.

By now both Clang (3.4) and gcc (4.9) are well compliant with the latest ISO C c11 standard. (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3631.pdf)

Include the following:

-std=c11

Let the compiler help you write good clean code

Learn from the warnings the compilers give you, and make sure you understand why it is complaining. Of course, If you get a warning, don’t disable the warning and instead fix the code.

Include, for example, the following:

-Wall -Wextra -Wpedantic

Trust in the compiler to do it’s job 

Donald Knuth said “premature optimization is the root of all evil”. This was true 1974 and is probably equally true today. Don’t try to outsmart the compiler. Don’t try to explicitly tell it to predict branches, unroll loops, inline functions, and so forth. Don’t write ++x instead of x++ because you think it will make your code faster and better.

In general write simple, natural code and don’t make assumptions about what will perform well or not. In the absolute majority of the cases you will be wrong, and the compiler will do a much better job than you at optimizing it. Indeed let the compiler optimize your code for you, but don’t try to tell it how to do it.

If optimization is needed, do proper profiling and learn how to find out what parts of your code that need to be optimized. Then do actual benchmarking of different alternative approaches to optimize the critical sections. Very often what you imagined would be the fastest code, turns out not to be that at all.

Include the following:

-O3

CFLAGS

In short I typically use the following when compiling object files from C. These flags work equally well with both gcc and Clang.

-std=c11 -Wall -Wextra -Wpedantic -O3
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s