Thursday, May 1, 2014

Basic Concepts for C Development

This is embarrassing to admit, but I didn't understand the basic needs of the compiler until recently. If you want to use make, automake or CMake (add whatever build system you want to use for compiling your C projects) to manage your projects, you need to have a mental model of what is going on. Without this model I have ended up spending hours just trying to figure out how to make my code compile with another library that I am playing around with.

When we write a C program, the compiler needs to be aware of where the headers are located, where the libraries that we are linking against are located and the source code that we want to build. All other details are less significant. The standard library is a blessing because you don't have to tell the compiler where to look for it as it already has the path built in.

Once you start working with other libraries this is no longer the case. To compile programs to use ncurses for example you need to add the -lncurses flag to the compiler. If you are dealing with SDL or GTK, you need to add more flags not only to indicate what library to link with (-l), but also other things that need to be defined for the library to work (i.e., GNU extensions). Programs like pkg-config will take care of this for you.

What has probably tripped me up the most though is knowing how stuff is included. When you use the preprocessor directive #include <yourheader.h>, it will search for that header in the standard include path. Being able to specify the include path is helpful when you want to select specific library versions such as including GTK2 over GTK3 or vice versa. The compiler is told where to include from using the -I directive. To be as accurate as possible #include "yourheader.h" allows you to look in the standard path and then the current directory you are working out of.

Knowing these things is important when telling your makefile where it needs to go to find these things so that you don't have to compile everything by hand. Without knowing these basics you will spend a lot of time fighting to compile rather than solving problems.