📅  最后修改于: 2023-12-03 14:41:42.720000             🧑  作者: Mango
Hello world is a simple program that is often used as a first step for learning a programming language. In this article, we will discuss how to write the "Hello world" program in C++.
Before we begin, make sure that you have a C++ compiler installed on your system. You can use any compiler that supports C++11 or later versions.
#include <iostream>
int main() {
std::cout << "Hello, world!\n";
return 0;
}
The program above is the standard C++ "Hello world" program. Let's go through it line by line to understand what is happening.
#include <iostream>
: This line includes the iostream header file, which contains the input-output stream functions like std::cout
and std::cin
.int main()
: This is the main function of the program, and it is where the program begins executing. int
is the return type of the function, which indicates that the function returns an integer value. main()
is the name of the function, and the empty parentheses indicate that the function takes no arguments.{}
: These curly braces enclose the body of the main()
function.std::cout << "Hello, world!\n";
: This outputs the string "Hello, world!" to the console using the std::cout
stream. The <<
operator streams the string to the console. The \n
at the end of the string indicates a new line character, which moves the cursor to the next line.return 0;
: This returns the integer value 0 from the main()
function, indicating that the program executed successfully.To compile the program, save it with the .cpp
extension in a file called hello.cpp
, and then use your C++ compiler to compile it. On Linux, you can use the g++
compiler:
g++ -o hello hello.cpp
This will create an executable file called hello
. To run the program, type:
./hello
This will output "Hello, world!" to the console.
Congratulations! You have successfully written and run a "Hello world" program in C++.