在cmd上运行C++程序

方法一:使用MinGW的G++编译器

  1. 首先创建一个名为 hello.cpp 的文件,内容如下:
#include <iostream>

using namespace std;

int main()
{
    cout << "hello" << endl;

    return 0;
}
  1. 将文件保存到一个目录中,此处保存到E:\c++_code

  2. 编译C++程序

    1. 打开命令提示符

      • 按 Win + R,输入 cmd,然后按 Enter 打开命令提示符。
    2. 导航到源代码目录

      • 使用 cd 命令导航到源代码目录,例如:
        cd e:\c++_code
        
        如图:
        img
    3. 编译代码

      • 使用 g++ 命令编译源代码,例如:

        g++ hello.cpp -o hello.exe
        

        在Windows系统中,也可写成(即可以忽略可执行文件的扩展名):

        g++ hello.cpp -o hello
        

        这条命令使用G++编译 hello.cpp 并生成 hello.exe 可执行文件。

      • 在目录处带来的变化:

        执行前

        img

        执行后

        img

        多了个hello.exe可执行文件

    4. 运行生成的可执行文件

      • 使用以下命令运行生成的可执行文件:

        hello.exe
        

        或者

        hello
        

        如图:

        img

方法二:使用Microsoft Visual C++编译器

若电脑里安装了Visual Studio,可以使用其自带的命令行工具 cl.exe 进行编译。

img

posted @ 2024-10-14 20:34  hisun9  阅读(4)  评论(0编辑  收藏  举报