CSUF Logo
optics.csufresno.edu Class Files - ECE 71 HOWTOs
Department of Electrical and Computer Engineering
Dr. Gregory R. Kriehn, Professor

HOWTO Compile a Program using gcc/g++

Background


The GNU Compiler Collection (usually shortened to GCC) is a compiler system supporting various programming languages produced by the GNU Project. GCC is a key component of the GNU toolchain. As well as being the official compiler of the GNU system, GCC has been adopted as the standard compiler by most other modern Unix-like computer operating systems, including GNU/Linux, the BSD family and Mac OS X. GCC has been ported to a wide variety of computer architectures, and is widely deployed as a tool in commercial, proprietary and closed source software development environments. GCC is also available for for most embedded systems, including ARM-based; AMCC, and Freescale Power Architecture-based chips. The compiler can target a wide variety of platforms.

          -- Wikipedia Entry on the GNU Compiler Collection

(GNU is a recursive acronym for "GNU's Not Unix" and is pronounced "guh-NEW".)

Compiling Programs using g++


In other words, GCC is a compiler collection to support the compilation C/C++ source code for Unix/Linux-based operating systems. To compile C++ programs, g++ will be used from the GCC compiler collection. The syntax for compiling C++ source code using the 2011 version of C++ is given by:

g++ -std=c++11 [infile] -o [outfile]

As an example, if you wish to compile a source file, such as distance.cpp, and create an executable file called distance.o, type:

~> g++ -std=c++11 distance.cpp -o distance.o

If you wish to compile a hw01.cpp, type:

~> g++ -std=c++11 hw01.cpp -o hw01.o

Please note that g++ is includes both a compiler and a linker, and g++ is able to compile your code and link object files together in a single step. The -o option is used to help specify the name of the output file.

Once compiled, you can execute your code by simply typing the name of your output file. The code will then execute:

~> hw01.o
The distance between points is:  3.61.
~>

Please note that each time you make changes to your source code, you will have to re-compile and re-link your code. If your code fails to compile, it will provide a list of errors and the lines that they occur on. Fix any errors before trying to re-compile your code. Warning! Just because your code compiles does not mean that it will execute properly!