Compiling C programs with gcc - an overview
Archive - Originally posted on "The Horse's Mouth" - 2008-06-10 07:04:58 - Graham EllisGcc - the "Gnu Compiler Collection" - is used to compile AND to link C language programs in an open source environment. A single command - gcc runs a series of phases that take you from source code through to an executable program file, with the actual steps taken works out based on:
• the extensions you give for the files
• command line options
Here are the phases:
1. The C preprocessor (cpp)
2. The C Compiler
3. The Link Loader (ld)
The C Preprocessor takes directives in the source file (that's lines that start with a # character) and acts on them as appropriate - "including" standard files of definitions, replacing "defined" constants via macros, and so on.
The C Compiler takes the preprocessor output and converts it from an ASCII English-like source code into binary code suitable for running on the particular target machine. But is is NOT a complete program yet - just a section of code / a component that needs to be joined to other components.
The last phase - the Link Loader takes all of your components, adds to them others from standard libraries, and creates a complete executable program.
Notes:
a) You'll usually run a whole series of preprocessors and compiles before running a single load, as most programs comprise many source files. Example:
gcc -c tom.c
gcc -c dick.c
gcc -c harry.c
gcc -o tom tom.o dick.o harry.o
In this example, each of three source files is compiled into an object file, and those object files are them joined into an executable file. The -c options is "compile only", and the -o option requests an output file of a none-default name.
b) If you fail to give a -o options on the gcc run that generates a program file, you'll produce a program file called a.out
c) You can do a compile and load all at once:
gcc -o tom tom.c dick.c harry.c
but as your program gets larger, that gets to be more and more repeated compile work when you'll only be changing one or two out of (perhaps) hundreds of source files at a time
d) You can use the make utility to store all your gcc - and other - commands used to build a program, and by noting down in that file a series of dependencies you can
• ensure that only the phases that need re-doing are done
• store the sometimes-complex gcc instructions so you don't have to keep retyping them.