How to run C, C++ program in Linux, Ubuntu. This question is asked by a reader on my Facebook page. He started using Ubuntu and written C program but he didn’t know how to compile and run this program.
In this post, I’ll show how to create, compile and run C, C++ Pprogram in Linux, Ubuntu.
How to Run C, C++ Program in Linux, Ubuntu
1. To run a C program in Linux we first need to install Build essential package. Build essential package install development libraries require for compilation.
In Ubuntu, we install packages through the apt-get package manager. If you are not familiar with apt-get then read my previous tutorial on a apt-get package manager.
1 2 |
sudo apt-get update sudo apt-get install build-essential manpages-dev |
After installation check GCC version by typing.
1 |
gcc --version |
1 2 3 4 |
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 Copyright (C) 2011 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. |
2. Let’s create a simple c program then we compile and run this program. To create a C program I am using vi editor. You can use any editor of your choice. Create and save this program. In next step, we compile this program.
1 |
vi firstprogram.c |
1 2 3 4 5 |
#include <stdio.h> void main() { printf("My first Program"); } |
In vi editor, we use wq command for save and exit. Type wq once your program is completed.
1 |
:wq |
3. Now compile this program.
1 |
cc firstprogram.c |
5. Once it compiles successfully, then you can execute this program using a.out .
1 |
./a.out |
How to Run C++ program in Linux
To compile and run C++ code, use following command.
1 |
g++ filename.c -o filename |
filename.c is the name of my C++ code file. Execute this file, once it compiles successfully.
1 |
./filename |