Using gcc

gcc is the dominant compiler used now for building C programs. It is a free (open source) program, being the first part of the gnu suite, upon which linux is built. Although gcc is used widely for C, it can also compile many other languages, including C++, fortran and java.

Compiling actually consists of several steps:

  1. Compile Convert the C (source) code into assembler.
  2. Assemble Convert the assembler code into binary instructions (a .o file)
  3. Link Combine each .o file, along with previously built .o files held in libraries, into a single executable program.

gcc can do all or any of these steps at a time. We will generally combine the first two, but step 3 independently.

Suppose you want to build a program that includes file1.c, file2.c and requires the math library. First you must compile (and assemble) file1.c and file2.c:

   gcc -c file1.c
   gcc -c file2.c
In these commands, the -c says compile (don't link yet) each file. If these two commands complete without error, you should now have files called file1.o and file2.o.

To combine these into the program called myprogram.exe, you use the following command:

   gcc -o myprogram.exe file1.o file2.o -lm
In this command, the -o option indicates what the program should be called (myprogram.exe in this case). Because there is no -c option, the program is linked, resulting in a program that can run. The -lm option says include the math library in the program.

To run this program, type