📅  最后修改于: 2023-12-03 14:59:45.017000             🧑  作者: Mango
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.
Before we begin, make sure you have the following:
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.
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.
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.
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.