【学习】windows下cmake学习(一)——hello world

前言

最近这段时间每天将抽出一小时左右学习cmake,参考github知名cmake开源项目:

https://github.com/ttroy50/cmake-examples

学习过程中思考与笔记会记录在此。

从标题可以看到,我的系统为windows,因此有一些路径或命令可能与linux有所冲突,因此请酌情围观。

操作系统:windows;

编辑器:vscode;

目录结构

A-hello-cmake
	├── CMakeLists.txt
	├── main.cpp

其中main.cpp仅为一个helloworld程序

#include <iostream>

using namespace std;

int main(){

    cout << "Hello World!" << endl;

    return 0;
}

编写CmakeLists

根据教程,其在CmakeList中设置了cmake最低版本即项目名称即可编译并运行。

# cmake最低版本
cmake_minimum_required(VERSION 3.5)

# 项目名称
project (A-hello_cmake)

# 创建一个可执行文件
add_executable(A-hello_cmake main.cpp)

但是在windows平台,不出意外你将遇到如下错误:

-- Building for: NMake Makefiles
CMake Error at CMakeLists.txt:5 (project):
  Running

   'nmake' '-?'

  failed with:
   系统找不到指定的文件。
   
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!

构建

解决上述问题,需要在初次构建时增加-G参数。

cmake -G "MinGW Makefiles" .
-- The C compiler identification is GNU 8.1.0
-- The CXX compiler identification is GNU 8.1.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: D:/Application_MinGW_w64/mingw64/bin/gcc.exe - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: D:/Application_MinGW_w64/mingw64/bin/c++.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.8s)
-- Generating done (0.0s)
-- Build files have been written to: E:/CodeSpace/Cpp_Study/A-hello-cmake

如果想要将构建结果输出至其他目录(如build),则增加-B参数,前提是已经创建好了build目录。

 cmake -G "MinGW Makefiles" -B .\build\
-- The C compiler identification is GNU 8.1.0
-- The CXX compiler identification is GNU 8.1.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: D:/Application_MinGW_w64/mingw64/bin/gcc.exe - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: D:/Application_MinGW_w64/mingw64/bin/c++.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.9s)
-- Generating done (0.0s)

编译

紧接上文中的-B build

我们只需要在/build目录下,执行make命令,即可完成编译。

make
[ 50%] Building CXX object CMakeFiles/A-hello_cmake.dir/main.cpp.obj
[100%] Linking CXX executable A-hello_cmake.exe
[100%] Built target A-hello_cmake

运行

make命令将根据CMakeLists.txt中编写的规则编译可执行文件,由于我们在编写CMakeLists节中,通过add_executable(A-hello_cmake main.cpp)指定了可执行文件的名称为A-hello_cmake,因此编译结束后可通过.\A-hello_cmake.exe运行。

.\A-hello_cmake.exe
Hello World!
posted @ 2023-09-11 00:28  小拳头呀  阅读(169)  评论(0编辑  收藏  举报