How to Compile C/C++ Program And Create an Executable File of C Program on Linux

This post will guide you how to compile a C or C++ program and create an executable file of a C program under Linux system. How to compile a c source code using GNU GCC compiler on CentOS/Ubuntu Linux system.

Assuming that you are a new Linux user and you wrote down a C program, and try to compile and run it. you need to install the GNU GCC compiler firstly, and run gcc command to compile it and create an executable file of c program. then you can run the executable file to get the result.

Check the Compiler is Installed on Linux System


You can check if you can run the gcc command or check if you can get the version of the gcc compiler to make sure the compiler is installed or not on your Linux system. Issue the following command via CLI:

$ which gcc
$ gcc --version
$ type -a gcc

Outputs:

devops@devops-osetc:~$ which gcc
/usr/bin/gcc
devops@devops-osetc:~$ type -a gcc
gcc is /usr/bin/gcc
devops@devops-osetc:~$ gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Compile C Program using GCC Compiler


You can refer to the following syntax to compile a C or C++ program using gcc:

gcc program.c -o program

Or

g++ program.C -o program

Or

make program

You can write the first one Hello world C program or C++ program via Vi/VIM text editor on Linux, appending the following line into c program file fio.c:

#include<stdio.h>
int main()
{
printf("hello world\n");
return 0;
}

Let’s compile this c program to generate an executable file of C program so that you can execute it directly. type one of the following command:

$ gcc fio.c -o fio

or

$ g++ fio.c -o fio

Or

$ make fio

outputs:

devops@devops-osetc:~$ make fio
cc fio.c -o fio
devops@devops-osetc:~$ ls fio
fio
devops@devops-osetc:~$

let’s run the executable file of c program you just created, type:

$ ./fio

outputs:

devops@devops-osetc:~$ ./fio
hello world

Video: Compile C or C++ Program and Create Executable file

See Also:

You might also like:

Sidebar



back to top