CSCI 1320 (Principles of Algorithm Design I):
gcc Hints and Tips
Caveat: Last updated in 2007. Use with caution!
Compiling with the gcc compiler
Preliminary notes
- In the following,
- Typewriter font (like this) denotes text you should
type exactly as shown,
- Italics (like this) denotes something
you should supply (e.g., a filename).
- Square brackets (like these []) enclose optional
text.
In typing a command, do not include the square brackets used to
denote optional text.
- See Unix Hints and Tips
for quick explanations of other Unix commands referenced here.
Using the compiler
The gcc command invokes a C compiler.
In its most basic form, the compiler is invoked like this:
gcc sourcefile
where sourcefile contains C source code.
This command compiles (and links) the source code to produce
an executable file a.out, which you can subsequently
execute by typing its name as a command.
The compiler also has many, many options.
To compile with one or more of these options,
invoke the command like this:
gcc [option1] [option2] .... sourcefile
Here are some of the most useful for beginning programmers:
- -o outputfile
Puts output in file
outputfile instead of a.out.
- -Wall
Issues warnings for questionable code.
For example, with this flag on, the compiler will usually
warn you if you have made the all-too-common mistake of using
the assignment operator (=) where you meant to
use the equality-test operator (==).
- -pedantic
Issues warnings for non-standard code, i.e., code that
is not guaranteed to work with all C compilers and not
just this one.
- -std=c99
Compiles code based on the C99 standard (rather than
the default C89).
You can read all about these options and many more in the man page
for gcc (which you can read with the command man gcc).
A shortcut
I recommend that you compile your programs using the
-Wall and -pedantic options, plus
-std=c99 if you want to use C99 features.
To avoid having to type all of that in for every program,
you can do the following:
- Create a text file called Makefile, in the same
directory with your source files, containing the single
line:
CFLAGS= -Wall -pedantic -std=c99
(Use a text editor to create this file.)
- To compile program program.c, issue the
command make program. (Note that
you leave off the .c suffix.)
This command
automatically invokes the gcc compiler
as if you had typed
gcc -Wall -pedantic -o program program.c
So you get the extra warnings, and the executable
is called program rather than a.out
(The make command is a powerful and flexible tool
whose capabilities are well beyond the scope of this guide,
and even beyond its man page.
If you are interested, consult a good book on Unix,
or equivalent online documentation, such as the
GNU documentation for make.)