The gcc Command: Compiling C Programs

gcc is the version of the cc command that we use in all programming classes. gcc is "Gnu cc", part of the "Gnu" software from the Free Software Foundation; similarly  gdb is the Gnu  debugger. To compile a C program, give it a filename ending in ``.c'', for example ``prog.c'' then compile it by typing:

        eris% gcc prog.c

This creates an executable file known as a.out. You can see this in your directory using the ls command, but don't try to edit "a.out", since the format is not one that can be viewed. If you type a.out alone on a line, followed by a carriage return, you will execute the program. If you want to give a specific name other than a.out to your executable file, say the name "runfile", you can compile with the -o flag:

        eris% gcc prog.c -o runfile

and now typing runfile alone on a line will execute the result. To be able to debug your program (as explained in the \index{gdb} article below), you would use the flag -g.

        eris% gcc -g prog.c -o prog

HINT: Do NOT name your program ``test.c'' or make an executable program called ``test!'' The Unix shell contains a ``built-in'' command called test and this will run instead of your program!

As you will learn in Chapter 4 of K&R, it is possible to have different routines of a single program in different files. The different files might be named as in the example of Chapter 4: main.c getop.c, stack.c and getch.c. Then you can compile all of these files at once into an executable file named calc, allowing for debugging use, by giving the command:

        eris% gcc -g main.c getop.c stack.c getch.c -o calc

This command will create "object" files in your directory, main.o, getop.o, stack.o and getch.o. These are files for which most of the compilation work has been done, but the final linked load into the executable is yet to be performed. Now if you need to modify a single one of these files to fix a bug, say stack.c, you can save a lot of time in recompiling by giving the command:

        eris% gcc -g main.o getop.o stack.c getch.o -o calc

By specifying the ".o" extension (suffix) on three out of the four modules named, the compilation step is skipped, only one module is compiled, and the result is link loaded together with the existing object files into calc.

In cs240 you will learn about the make command, which is a program that manages compiler options and program building.

NOTE: It is good practice to ask gcc for more warnings than it gives by default.

        eris% gcc -g -Wall prog.c -o prog
The Wall flag will give all (or almost all) warnings as well as errors. The makefiles for cs310 give more examples of options.



next up
Next: The gdb Command: Previous: The C Programming



System_Administrator
Mon Jul 27 15:20:53 EDT 1998