How To Compile C and C++ Applications with GCC?
GCC is de facto compiler UNIX and LINUX Operating Systems. GCC is acronym of GNU Compiler Collection. As the name Collection suggest GCC supports C, C++, Java, Ada, Go etc. In this post we will look how to compile C and C++ applications.
By default compiler related tools are not installed. We can install them from repositories easily like below.
Ubuntu, Debian, Mint, Kali:
$ sudo apt-get install gcc -y
As we see GCC is already installed.
CentOS, Fedora, Red Hat:
$ yum install gcc -y
What Is Compiling
Compiling is the process of creating executable files from source code. There are some intermediate states but we do not dive into them. For example to print some messages to the standard output a program is written which is consist of source codes. Then the program is is compiled with GCC to create new executable file which can be run in the Linux. Here is our source code:
We have following source code to compile which just print some text to the standard output.
$ gcc main.c
We have compiled our source code and a binary named a.out is created. Then we executed the new binary and it prints out message “Hello poftut” .
Set Output Filename
By default after compile operation the created executable file name will be
a.out as we have seen in previous example. We can specify executable file name for after compilation like below.
$ gcc main.c -o mybinary
If our program have some problems about performance or errors we need to debug it. To debug an application it must be compiled with debug options to add some debug data into the binary files. Keep in mind debug information will made binary slower and bigger in size.
$ gcc -g main.c -o mybinary
In previous example we have seen that debug information made the executable slower and higher in size. For production environment we need to make the executable more optimized. We can make code more optimized in performance and size with
-O parameters. But keep in mind that in rare situations optimization can make things worst.
$ gcc -O main.c -o mybinary
We have looked a simple source code but in real world project there are a lot of code files and external libraries. We should specify the library we have used in the related code file. We can provide external libraries with
$ gcc -O main.c -lm -o mybinary
-lm will provide C standard math library to be used in this application .
Check Code Quality
Gcc have a good feature which will give suggestions about the code quality. This option will check written code in a more strict manner. But the code should be correct in syntactically and compiled correctly. We will use
-Wall option to use this feature.
$ gcc -Wall main.c
Version is important aspect of compile operation. Because gcc gains, dismiss separate features in each version and modifying related configuration is important. The version of gcc can be get with
-v option. This will not provide only the version also give information the configuration of gcc.
$ gcc -v