How to Compile and Run C/C++ Code on Ubuntu

How to compile and execute C and C++ code on Ubuntu desktop and server. If you have Ubuntu you already have g++ installed, which is C and C++ compiler. To check g++ version, simply launch your terminal and run the following command.

g++ --version

Install g++, C and C++ compiler on Ubuntu

In case it g++ is not installed on your system, run the following command to install g++

sudo apt update 
sudo apt install g++
g++ --version

Write your C hello world code, using your favorite text editor.

// file name: test.c

#include <stdio.h>

int main()
{
	printf("Hello World\n");
	return 0;
}

Compile C code with g++

compile and run C code on ubuntu
compile and run C code on ubuntu

Navigate to test.c and test.cpp directory using your terminal and run the following commands.

g++ test.c -o testc

Here -o flag is given to output executable file name

Run / Execute C program with terminal

./testc

Write your C++ hello world code

// file name: test.cpp
#include <iostream>

using namespace std;

int main(){
cout << "Hello World\n";

return 0;
}

Compile C++ code with g++

compile and run C++ code on Ubuntu
compile and run C++ code on Ubuntu

Navigate to test.c and test.cpp directory using your terminal and run the following commands.

g++ test.c -o testcp

Here -o flag is given to output executable file name

Run / Execute C++ program with terminal

./testcp

Watch me Compile and Execute C++ on Ubuntu

Watch me Compile and Execute C++ on Ubuntu

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.