📜  c++ hello world linux - C++ (1)

📅  最后修改于: 2023-12-03 14:59:45.017000             🧑  作者: Mango

C++ Hello World on Linux

In this guide, we will learn how to write a simple "Hello World" program in C++ on Linux. We will also cover how to compile and execute the program.

Prerequisites

Before we begin, make sure you have the following:

  • A Linux-based operating system (e.g., Ubuntu, CentOS, Fedora)
  • A C++ compiler installed (e.g., GCC, Clang)
Writing the Code

Let's start by creating a new file called hello.cpp and open it in a text editor. We will write our C++ code in this file.

#include <iostream>

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

The code above is a basic "Hello World" program in C++. It includes the <iostream> library, which allows us to use the std::cout object to print the message to the console. The main() function is the entry point of the program, where the execution begins.

Save the file and close the text editor.

Compiling the Code

Now, let's open a terminal and navigate to the directory where you saved hello.cpp. To compile the code, enter the following command:

g++ hello.cpp -o hello

This command will use the g++ compiler to compile hello.cpp and generate an executable file called hello. The -o option specifies the output file name. If the compilation is successful, you should see no error messages.

Running the Program

To execute the program, enter the following command in the terminal:

./hello

You should see the output Hello, World! printed on the console.

Congratulations! You have successfully written and executed a "Hello World" program in C++ on Linux.

Conclusion

In this guide, we have covered the steps to create a basic C++ program on Linux. We wrote a simple "Hello World" program, compiled it using g++, and executed it from the terminal. This serves as a foundation for more complex C++ projects on Linux.