Till a few years back, it was really difficult to obtain a free version of a compiler to run on ones machine to learn C or C++. And one had to resort to using a commercial compiler either by paying money and buying a licence or using a pirated copy of the same. I still remember, many years back, Borland C was considered to be the best compiler in the market for windows platform but later Microsoft's Visual-C usurped it to take the most popular position. Then GNU/Linux got wider acceptance and the rest as they say is history.
A majority of Linux distributions ship with the gcc suite of compilers. GCC stands for GNU Compiler Collection. And it contains compilers for various languages such as C,C++, and Java. It is one of the most efficient free implementation of a compiler one can hope to get and is available for multiple platforms and OSes including Windows.

How to compile a program

Here I will list the basic steps needed to compile a C / C++ program using GCC.

Check the version of the GCC compiler installed on your Linux machine.

$ gcc -v

Running the above command will give you an output similar to the one below.

If there are no syntax errors, the program will be successfully compiled and the compiler will create an executable file called a.out in your current directory. To run the freshly compiled program, just run a.out as you will any executable file.

$ ./a.out

As you can see I have used a ./ in front of a.out file. This is necessary if your current directory is not included in the PATH environment variable.

But if you want the compiler to give a different name to the executable file it generates, then you use the -o switch:

$ gcc -o test test.c

This will create an executable file by name test instead of a.out .

But sometimes it is necessary to get an assembly code listing of ones program. This is desirable if we need to say, get an idea of the values stored in the registers. This is also possible in gcc using the -S switch.

$ gcc test.c -S -g

The above command will create a text file called test.s which contains the assembly code of our program. The -g flag is optionally used to produce debug symbols and line number information.

You can optimize the compiler using the -O flag followed immediately by a number (between 0 and 3) which states the level of optimization. It is good to optimize ones programs as it results in faster binaries.

$ gcc -O2 -o test test.c

It is worth noting that one can turn off the optimization by using the -O0 switch.

For C++ programs, the gcc suite has another compiler by name g++. All the options which have been explained above works with the g++ compiler too.

The steps detailed above are more useful for C/C++ developers and students interested in learning to program in C/C++ rather than users of Linux. This is because the compiling of source code is made simple in GNU/Linux by the use of the make command.