Compile and Run C/C++ Programs on Linux

This post provides instructions how to compile and run c/C++ code on Linux.

Check whether gcc is installed

The following commands will display the installation path and version of gcc compiler.

$ whereis gcc
$ which gcc
$ gcc -v


Compile And Run C/C++ Programs In Linux

Write your code/program in your favorite text editor . Use extension .c for C programs or .cpp for C++ programs.

Here is a simple ā€œCā€ program.

$ cat hellow.c
#include <stdio.h>
int main()
   printf("hello world!");
   return 0;

To compile the program, run:

$ gcc hello.c -o hello1


$ g++ hello.c -o hello1

In the above example, we used C++ compiler to compile the program. To use C compiler instead, run:

$ cc hello.c -o hello1

If there is any syntax or semantic errors in your code/program, they will be displayed on the screen. You need to fix them first to proceed further.

If there is no error then the compiler will successfully generate an executable file named hello1 in the current working directory (where you put the source c/c++ file).

Now you can execute the program using the following command:

$ ./hello1

To compile multiple source files (e.g., source1 and source2) into executable, run:

$ gcc sourcecode1.c sourcecode2.c -o executable

To allow warnings, debug symbols in the output:

$ gcc sourcecode.c -Wall -Og -o executable

To compile the source code into Assembler instructions:

$ gcc -S sourcecode.c

To compile the source code without linking:

$ gcc -c sourcecode.c

The above command will create a executable called sourcecode.o.

If your program contains math functions:

$ gcc sourcecode.c -o executable -lm

For more details, refer the man pages.

$ man gcc


Leave a Reply

Your email address will not be published. Required fields are marked *