📜  c++ in cmd - C++ (1)

📅  最后修改于: 2023-12-03 15:13:54.337000             🧑  作者: Mango

C++ in CMD

In this guide, we will explore running and compiling C++ programs in the Command Prompt/Command Line (CMD). The Command Prompt is a command-line interpreter available in the Windows operating system, and it allows developers to interact with the computer system by running commands and executing programs.

Setting up the Environment

Before we can start using CMD for C++ development, we need to ensure that the necessary tools are installed. Here are the steps to set up the environment:

  1. Install a C++ compiler: One of the most popular C++ compilers for Windows is Mingw-w64. Download and install the Mingw-w64 compiler from the official website.

  2. Add compiler to the System Path: After installing Mingw-w64, add the compiler's bin directory to the system's PATH environment variable. This will allow CMD to find and execute the compiler from any directory.

  3. Verify installation: Open a CMD window and type g++ --version to verify that the compiler is installed and properly configured.

Creating and Compiling a C++ Program

Now that we have the environment set up, let's create a simple C++ program and compile it using CMD:

  1. Open a text editor and create a new file hello.cpp with the following code:
#include <iostream>

int main() {
    std::cout << "Hello, World!";
    return 0;
}
  1. Save the file to a directory of your choice.

  2. Open a CMD window and navigate to the directory where the hello.cpp file is saved.

  3. Compile the program by running the following command:

g++ hello.cpp -o hello.exe
  1. If there are no syntax errors in your code, this command will generate an executable file named hello.exe in the same directory.
Running the Compiled Program

Now that we have the hello.exe file, let's run it using CMD:

  1. In the CMD window, navigate to the directory where hello.exe is located.

  2. Run the program by simply typing its name and pressing Enter:

hello.exe
  1. The program will be executed, and you will see the output Hello, World! printed in the CMD window.

Congratulations! You have successfully created and run a C++ program using CMD.

Conclusion

In this guide, we covered the basics of using CMD to compile and run C++ programs. Setting up the environment, creating a program, compiling it using the Mingw-w64 compiler, and running the compiled executable were all discussed. With this knowledge, you can now start exploring the vast world of C++ programming using the command line.