Windows下搭建C++開發環境:MinGW+CMake

安裝CMake

下載地址:官網,選擇自己系統對應的版本
命令行窗口輸入"cmake",若顯示如下,則安裝成功。
cmake命令行

安裝MinGW

下載鏈接:這裏
默認安裝路徑是"C:\MinGW"。安裝完成後,打開MinGW Installation Manager,點擊左邊Basic Setup,右擊右邊的mingw32-base和mingw32-gcc-g++,選擇Mark for Installation,然後點擊菜單欄Installation-Apply Changes
MinGW界面
接下來,設置系統環境變量,將"C:\MinGW\bin"添加到Path。
命令行窗口輸入"gcc --version"或"g++ --version",若出現版本則安裝成功。
gcc版本

實例

編寫源碼文件:main.cpp

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

編寫CMake文件:CMakeLists.txt

cmake_minimum_required(VERSION 3.9)
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 "E:/project/build/CMakeFiles/CMakeOutput.log".

解決方法:在MinGW的安裝目錄下的bin文件夾中找到mingw32-make.exe,複製一份並改名爲make.exe。
再次運行cmake -G"Unix Makefiles" ../就不再出錯了。

編譯

$ 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章