Using the GNU C++ Compiler

Overview

The GNU Compiler Collection (GCC) is an integrated collection of compilers for several languages, including C, C++, Java and Fortran.

Our interest here is with the C/C++ compiler .

Syntax

The g++ command has the following syntax:

g++ [-option…] file… [option file]…

where option denotes an option or switch (see below) and file denotes a file name.

Options

The list of valid options/switches for the g++ command includes the following:

OptionPurpose
cCompiles without linking
Dname=definitionDefines a symbol (as with #define)
EStop after the preprocessing stage
gProduce debugging information
ISearches the given directory for “includes”
llibnameSearches the specified library when linking
ofilenameNames the output file
MInstead of preprocessing, output a rule suitable for use by make
-helpProvides (some) help
-versionDisplays the version number

Examples

The following command compiles (but does not link) the C source file named test.c and creates the file test.o:

g++ -c test.c

The following command first defines the symbol DEBUG in the C++ source file named Demo.cpp and then compiles and links it (creating an executable file named Demo).

g++ -DDEBUG=VERBOSE Demo.cpp -o Demo

The following command “includes” files from the directory /myfiles/include in addition to the standard INCLUDE directory.

g++ -I/myfiles/include Demo.cpp -o Demo

The following commands first compile the source files for a small application (written in C) and then links them into an executable named example.

g++ -c account.c
g++ -c example.c
g++ example.o account.o -o example

Error and Warning Messages

Error and warning messages generated by the GCC are often less than clear. There are several places you can go for help, including: