这里主要介绍gcc编译运行C++程序。
设置系统环境变量
在我的电脑单击右键,选择属性,选择高级系统设置,选择环境变量,在系统环境变量中找到path,新建一个变量,表明gcc.exe所在的位置,一般情况下都是找到自己IDE安装的位置,然后找到mingw,进入bin目录,你可以发现gcc.exe:
D:\Cfree5\mingw\bin #这是我电脑上的位置,根据安装的不同
设置好之后可以在cmd中测试,输入gcc应该是可以识别的,而不是提示说gcc不是内部命令。
编辑程序
新建一个文件,编辑程序并保存,取名为test.cpp存放在一个文件夹中,我存放在D:\code\下:
#author:MrBread
#date:2017-6-14
#function:test the gcc
#include<iostream>
using namespace std;
int main(){
cout<<"Hello World"<<endl;
return -1;
}
在命令行下编译运行程序
打开命令行cmd:
> d:
> cd code
> gcc -o test test.cpp
C:\Users\MrBread\AppData\Local\Temp/ccYRt1o3.o:test.cpp:(.text+0xd): undefined reference to `std::string::size() const'
C:\Users\MrBread\AppData\Local\Temp/ccYRt1o3.o:test.cpp:(.text+0x60): undefined reference to `std::string::operator[](unsigned int) const'
C:\Users\MrBread\AppData\Local\Temp/ccYRt1o3.o:test.cpp:(.text+0x9e): undefined reference to `std::string::operator[](unsigned int) const'
C:\Users\MrBread\AppData\Local\Temp/ccYRt1o3.o:test.cpp:(.text+0xcc): undefined reference to `std::string::operator[](unsigned int) const'
C:\Users\MrBread\AppData\Local\Temp/ccYRt1o3.o:test.cpp:(.text+0x14d): undefined reference to `std::ios_base::Init::Init()'
C:\Users\MrBread\AppData\Local\Temp/ccYRt1o3.o:test.cpp:(.text+0x168): undefined reference to `std::ios_base::Init::~Init()'
collect2: ld returned 1 exit status
从上面我们可以看出程序出错,我百度之后发现要加上参数如下,具体可以参考undefined reference:
>gcc test.cpp -lstdc++ -o test
无任何输出,说明编译成功,yes!
接下来输入test:
>test
Hello world
可以看到程序正常执行。good job!
执行以下指令查看程序运行状态:
>echo %ERRORLEVEl%
-1
这是因为我在程序最后写的是:
return -1;
end