Introductory tutorial on g++: Getting started

g++ GNU C++ compiler is a compiler in  Linux which is used to compile the C++ programs. It compiles .c and .cpp programs. 

I am writing this tutorial to demonstrate g++ on the ubuntu platform. 
g++ can be installed in Ubuntu by the following command: 
sudo apt-get install g++ 
To access the g++ version the following command is used
g++ –version 
G++ help: 
g++ –help 
A hello world program is created that prints “Hello World g++”. 
The code is compiled with the command: 
g++ hello.cpp
A default executable called ./a.out will be created. When we run the a.out file we can view the output. 
Now, When we introduce a new variable ‘int i’ and not use it, then the warning should appear. To view the warning message the following command can be used:
g++ hello.cpp -Wall
-Wall prints all the warning messages generated during the compilation. 
Another useful command is to compile, link the file, and generate an executable with the target name specified. 
g++ -o hello.exe hello.cpp
We can learn the next step when there are multiple files and they need to be linked to a single executable. 
Before that let me give some background on :
-c flag translates the source code to object code
-o flag links the object code to the executable. 
We can include another header file called hello.h which declares the function in another file next.cpp which has code to print another line. 
hello.cpp
#include <iostream> #include “hello.h” int main(){ std::cout << “Hello World g++” << std::endl; nextLink(); return 0;}
hello.h 
void nextLink();



next.cpp
#include <iostream> using namespace std; void nextLink(){ cout<<“This is a demo of multiple files being linked”<<endl; return ;}


There are 2 steps in the compilation : 
g++ -c hello.cpp next.cpp
This generates the .o file. 
g++ -o print hello.o next.o
This generates an executable named print. When the print is run the following output is printed.