Linux Command Line: g++

Written by:  • Edited by: Michael Dougherty
Updated Dec 21, 2008
• Related Guides: Microsoft | Linux Command Line | Linux

For many studying a programming language the tools can be very costly. Fortunately Linux has some outstanding tools to help you compile your applications. In this entry to the Brighthub Linux Command Line series you will learn how to compile C++ with the help of g++.

What is g++

The g++ compilation tool is a part of the gcc suite that is used to compile both C and C++ code. The g++ command line does preprocessing, complation, assembly, and linking. The g++ command is very easy to use and does its job much faster than any GUI alternative. Using g++ is a great alternative for those who need a free alternative to Microsoft Studio applications.

Basic Usage

First and foremost you must know that g++ has a TON of options and switches. So many it can be rather overwheming. To avoid scaring anyone from using g++, I will stick with simplicity and illustrate how to compile a simple "hello world" C++ code. This will serve to illustrate how simple compiling with g++ can be.

With that said let's take a look at compilation. As I said we will use a simple "Hello World" snippet of code. Here's the code:

#include <iostream>

int main()

{

std::cout << "Hello Brighthub!\n";

}

This file will be called test.cpp.

With that file in place the command:

g++ -o test test.cpp

This will compile, assemble, and link the application. The "-o" switch instructs g++ to place the output of the compilation into the file that follows "-o". This output will effectively be the name of the compiled application, which will in turn be the binary application created by the compilation. In order to run the application you will need to change the permissions of the file with the command:

chmod u+x test

To run this newly created application you only need to issue the command (from within the directory housing the file) ./test. In our sample you should see the output:

Hello Brighthub!

If you are interested in seeing what is happening during the compilation you can add the "-v" argument like so:

g++ -v -o test test.cpp

With the above command you will see a lot of text scroll by telling you what exactly is going on.

Final Thoughts

Being able to compile C++ code with g++ enabled me to get through C++ class. Without having to spend more money than a student should have to on a program. The g++ tool is an outstanding way to compile C and C++ applications on a Linux machine.


 
blog comments powered by Disqus
Email to a friend