Skip to content

[Linux][C++] How to compile and execute a C++ program

C++ is a veteran programming language developed in 1979. In 1998, there was the first C++ standard specification, and it is also the most widely used programming language in system programming languages as far as I know.

Nowadays, even if languages like Java, Python, Go, Swift … etc. catch up quickly, C/C++ is still one of the most popular programming languages, and it is still the first programming language many people have learned.

But if you ask me how to learn a programming language, I almost recommend Python. The performance of Python is not as good as the compiled language, but the writing method is simple and elegant, and easy to use.

The topic is far off. This article mainly records how to compile a simple C++ program that prints out Hello World on Linux, and execute the compiled file.


Compiler Installation

If you have no compile in your system, you can use the following command to install it. (If you have no VIM editor either, you can also install it by the way.)

sudo apt install g++ build-essential
sudo apt install vim

Print “Hello World”

This is a simple sample code to test the compiler, so we just choose to print “Hello World“.

First, we need to open a cpp file in terminal:

vim hello_world.cpp

And we write down:

#include <iostream>
using namespace std;


int main() {
    cout << "Hello World!" << endl;
    return 0;
}


Use Esc + :wq to save the file, and enter the following command in the terminal (Note: that it must be under the folder with hello_world.cpp)

g++ hello_world.cpp -o hello_world.out

After the compilation is over, you should see an extra file called hello_world.out in the current directory. Use the following command to execute in the terminal:

./hello_world.out

Output:

Hello World!

In this way, it is confirmed that the current environment can compile C++ program. Congratulations!


References

Tags:

Leave a Reply