Theory
GCC (GNU Compiler Collection) is a set of compilers developed by the GNU project that support a lot of languages, a lot of different achitectures, and provides the basic layer for software development in most Free operating systems. GCC includes frontends for C, C++, Onjective C, Java, ADA and Fortran, although there are other non-standard frontends also available.
GCC is used to transform the source code of the programs into some executable binary files that can be understood by the computer. Programs coded in C usually have the extension ".c", while its header files usually end in ".h". Those coded in C++ might have extensions like ".cpp", ".cxx", ".cc" or just with a capital letter ".C". The extensions ".f" or ".for" belong to fortran, ".s" and ".S" to assembler code, and so on.
The general syntax for compiling a program with gcc is "gcc [ option | filename ]..." for programs in C, and "g++ [ option | filename ]..." for programs in C++
GCC supports many, many options. The most commonly used are:
- -o filename : Place output in file "filename".
- -c : Compile or assemble the source files, but do not link.
- -g : Produce debugging information.
- -Wall : Give a warning message whenever something is strange in the code.
- -Werror : Treat warnings as if they were errors.
- -O0 : Do not optimize.
- -O2 : Turns on all of these optimizations except ‘-funroll-loops’ and ‘-funroll-all-loops’.
- -O3 : Optimize even more. This optimizations can be problematic in some architectures, and the result may not be as good as with -O2. It varies case by case, but as a general rule Debian packages are built conservatively with just -O2.
- -Os : Optimize for size (i.e. try and make a smaller executable).
- -llibrary : Use the library named library when linking.
- -Idir : Append directory dir to the list of directories searched for include files.
- -Ldir : Add directory dir to the list of directories to be searched for the libraries referenced in a ‘-l’ option.
Exercises
Lets try to compile the simplest program in C. You can write it in your favourite editor, or just cat it directly from the console into a file (CTRL-D for EOF):
$ cat >test.c
#include <stdlib.h>
#include <stdio.h>
- int main()
- {
- printf("Hello, World\n");
- return 0;
- }
Now we have a small C program in the file test.c, it doesn't matter too much if you don't understand it, don't worry.
Even though it's possible to compile it into a final executable in a single command, the process is really done in different phases, and it's quite usual to separate explicitly the compilation into binary objects (with the extension .o), and the final linking of these objects into a binary executable:
Compile the program:
- $ gcc -Wall -c -o test.o test.c
Link the program:
- $ gcc -o test test.o
Execute the program
- $ ./test