在cmd上运行C++程序
方法一:使用MinGW的G++编译器
- 首先创建一个名为
hello.cpp
的文件,内容如下:
#include <iostream>
using namespace std;
int main()
{
cout << "hello" << endl;
return 0;
}
-
将文件保存到一个目录中,此处保存到
E:\c++_code
。 -
编译C++程序
-
打开命令提示符
- 按 Win + R,输入 cmd,然后按 Enter 打开命令提示符。
-
导航到源代码目录
- 使用 cd 命令导航到源代码目录,例如:
如图:cd e:\c++_code
- 使用 cd 命令导航到源代码目录,例如:
-
编译代码
-
使用 g++ 命令编译源代码,例如:
g++ hello.cpp -o hello.exe
在Windows系统中,也可写成(即可以忽略可执行文件的扩展名):
g++ hello.cpp -o hello
这条命令使用G++编译 hello.cpp 并生成 hello.exe 可执行文件。
-
在目录处带来的变化:
执行前
执行后
多了个
hello.exe
可执行文件
-
-
运行生成的可执行文件
-
使用以下命令运行生成的可执行文件:
hello.exe
或者
hello
如图:
-
-
方法二:使用Microsoft Visual C++编译器
若电脑里安装了Visual Studio,可以使用其自带的命令行工具 cl.exe 进行编译。