Hello World - First C++ Program
Writing your first C++ program, the classic "Hello, World!" program, is a fundamental step in learning the language. Here's a step-by-step guide along with an example:
Set Up Your Development Environment
Ensure you have a C++ compiler installed on your system. If you don't have one, you can install GCC on Linux using sudo apt install g++ (for Debian-based systems) or sudo yum install gcc-c++ (for Red Hat-based systems). On Windows, you can use Visual C++ through Visual Studio or install MinGW.
Create a New C++ Source File
Open a text editor or an Integrated Development Environment (IDE) like Visual Studio Code, Code::Blocks, or CLion.
Create a new file with a ".cpp" extension, for example, "hello.cpp".
Write the C++ Code
In your C++ source file, write the following code:
Let's break this code down:
- #include <iostream>: This line includes the standard input/output library, which provides functionality for printing text to the console.
- int main() { ... }: This is the main function, the entry point for your program.
- std::cout << "Hello, World!" << std::endl;: This line uses the std::cout object to print "Hello, World!" to the console.
- return 0;: This line indicates that the program has executed successfully.
Save the File
Save your C++ source file.
Compile the Code
- Open a terminal or command prompt.
- Navigate to the directory where your source file is saved.
- Compile the code using the C++ compiler (e.g., g++ on Linux):
Run the Program
After successful compilation, you'll have an executable file (e.g., "hello" in this case).
Run the program by typing its name and pressing Enter:
Observe the Output
You should see "Hello, World!" printed to the console.
By following these steps, you've successfully written, compiled, and executed your first C++ program, displaying the famous "Hello, World!" message. This simple program provides an essential foundation for understanding C++ syntax and how to create and run C++ applications.
Conclusion
Writing your first C++ program, the "Hello, World!" program, involves setting up a development environment, creating a C++ source file, writing a simple program that prints "Hello, World!" to the console, saving the file, compiling it using a C++ compiler, and running the resulting executable. This fundamental exercise introduces the essential steps for coding, compiling, and executing C++ programs, providing a foundational understanding of the language.