Categories
Ubuntu

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

By Tube Mint

I am a YouTuber and I also do niche marketing. In the process of create my niche blog using WordPress, Drupal, and GatsbyJS, I learned a few things like html, css, JS, CMS, MVC frameworks, C++, Python, Ruby, MySQL, Windows and Linux. After some time.. I realized that I can share my knowledge with people on YouTube and through my blog. So, here I am. You can ask me if you have any question about these technologies.
Thanks,
@TubeMint