CS 1320 (Principles of Algorithm Design I):
g++ Hints and Tips
Compiling with the g++ 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 g++ command invokes a C++ compiler.
In its most basic form, the compiler is invoked like this:
g++ 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:
g++ [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.
You can read all about these options and many more in the man page
for g++ (which you can read with the command man g++).
(A note to the picky: Some options are actually documented in the
man page for gcc, which is the C compiler on which g++
is based.)
A shortcut
I recommend that you compile your programs using the
-Wall and -pedantic options.
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:
CXXFLAGS= -Wall -pedantic
- To compile program program.cc, issue the
command make program. (Note that
you leave off the .cc suffix.)
This command
automatically invokes the g++ compiler
as if you had typed
g++ -Wall -pedantic -o program program.cc
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.)