windows+CMake+mingw 搭建c c++开发环境 (2)

安装完成

环境变量设置

同CMake的一样,mingw安装完后自动了设置环境变量,你也可以通过运行其安装目录下的mingw-w64.bat来进入运行环境

mingw-w64.bat

验证mingw环境是否设置好,同样新调出CMD窗口,输入gcc命令,出入如下信息则表示安装没有问题,否则请参照CMake配置环境变量的方式来解决。

gcc 命令

CMake+mingw 实例

我们安装完环境后来个实例运行下吧

编写源码文件
来个宇宙最著名的程序吧

#include <stdio.h> int main() { printf("hello\n"); return 0; }

编写CMake文件

cmake_minimum_required(VERSION 3.0) project(Hello) set(SOURCE main.cpp) add_executable(${PROJECT_NAME} ${SOURCE})

生成Make file

mkdir build cd build cmake -G"Unix Makefiles" ../

很不幸,这一步会出问题

CMake Error: CMake was unable to find a build program corresponding to "Unix Makefiles". CMAKE_MAKE_PROGRAM is not set. You probably need to select a different build tool. CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage -- Configuring incomplete, errors occurred! See also "D:/tmp/build/CMakeFiles/CMakeOutput.log".

意思就是不能生成Unix Makefiles,这是缺少make程序造成的,
解决方法就是找到mingw安装目录下mingw32-make.exe拷贝一份并重命名为make.exe

make

再运行cmake -G"Unix Makefiles" ../

$ cmake -G"Unix Makefiles" ../ -- The C compiler identification is GNU 7.2.0 -- The CXX compiler identification is GNU 7.2.0 -- Check for working C compiler: C:/Program Files (x86)/mingw-w64/i686-7.2.0-posix-dwarf-rt_v5-rev1/mingw32/bin/gcc.exe -- Check for working C compiler: C:/Program Files (x86)/mingw-w64/i686-7.2.0-posix-dwarf-rt_v5-rev1/mingw32/bin/gcc.exe -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: C:/Program Files (x86)/mingw-w64/i686-7.2.0-posix-dwarf-rt_v5-rev1/mingw32/bin/c++.exe -- Check for working CXX compiler: C:/Program Files (x86)/mingw-w64/i686-7.2.0-posix-dwarf-rt_v5-rev1/mingw32/bin/c++.exe -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Configuring done -- Generating done -- Build files have been written to: D:/tmp/build

这样就对了

编译

make

什么,又有问题

$ make /usr/bin/sh: -c: line 0: syntax error near unexpected token `(' /usr/bin/sh: -c: line 0: `C:/Program Files (x86)/mingw-w64/i686-7.2.0-posix-dwarf-rt_v5-rev1/mingw32/bin/make -f CMakeFiles/Makefile2 all' make: *** [Makefile:84: all] Error 1

还记得前面我们安装mingw时说的坑吗,现在我们需要填坑了,文件就是万恶的C:/Program Files (x86),这也好办,将mingw-w64文件夹复制到一个正常的目录吧,比如直接C:/mingw-w64,然后需要修改环境变量

修改mingw环境变量

$ make Scanning dependencies of target Hello [ 50%] Building CXX object CMakeFiles/Hello.dir/main.cpp.obj [100%] Linking CXX executable Hello.exe [100%] Built target Hello

运行

$ ./Hello.exe hello

好了,终于成功了

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsspjx.html