Windows命令行使用CMake
Dionysen

使用CMake命令行构建一个小工程

编辑main.cpp

#include <iostream>
int main() {
std::cout << "Hello, Windows!\n";
return 0;
}

编辑CMakeLists.txt

cmake_minimum_required(VERSION 3.5.1)
project(win32 VERSION 0.1.0)
set(CMAKE_CXX_STANDARD 20)
include(CTest)
enable_testing()

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_BUILD_TYPE Debug)

include_directories(includes)
add_executable(win32 main.cpp)

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

当前目录为:

    目录: D:\proj


Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2023/6/20 9:47 build
-a---- 2023/6/20 9:51 372 CMakeLists.txt
-a---- 2023/6/20 9:37 97 main.cpp

进入build文件夹:

PS D:\proj> cd .\build\

输入命令cmake ..以创建CMakeCache:

PS D:\proj\build> cmake ..
-- Building for: Visual Studio 17 2022
-- Selecting Windows SDK version 10.0.22000.0 to target Windows 10.0.19045.
-- The C compiler identification is MSVC 19.36.32534.0
-- The CXX compiler identification is MSVC 19.36.32534.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: E:/VS2022/VC/Tools/MSVC/14.36.32532/bin/Hostx64/x64/cl.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: E:/VS2022/VC/Tools/MSVC/14.36.32532/bin/Hostx64/x64/cl.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (7.5s)
-- Generating done (0.1s)
-- Build files have been written to: D:/proj/build

输入命令cmake --build .编译:

PS D:\proj\build> cmake --build .
MSBuild version 17.6.3+07e294721 for .NET Framework

1>Checking Build System
Building Custom Rule D:/proj/CMakeLists.txt
main.cpp
win32.vcxproj -> D:\proj\build\Debug\win32.exe
Building Custom Rule D:/proj/CMakeLists.txt

此时可以看到build文件夹下多出了许多文件和一些文件夹:

    目录: D:\proj\build


Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2023/6/20 9:57 CMakeFiles
d----- 2023/6/20 9:57 Debug
d----- 2023/6/20 9:56 Testing
d----- 2023/6/20 9:57 win32.dir
d----- 2023/6/20 9:57 x64
-a---- 2023/6/20 9:56 45092 ALL_BUILD.vcxproj
……

其中Debug文件夹中就有生成的可执行文件:

PS D:\proj\build> cd .\Debug\
PS D:\proj\build\Debug> ls


目录: D:\proj\build\Debug


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2023/6/20 9:57 58368 win32.exe
-a---- 2023/6/20 9:57 1265664 win32.pdb

运行:

PS D:\proj\build> .\Debug\win32.exe
Hello, Windows!

CMake使用glut库

点此下载glut的bin文件,其中包含头文件、.dll.lib文件,将其放到需要引用的工程中。

stdlib.h(56,48): error C2381: “exit”: 重定义;”noreturn” 不同 [D:\proj\build\win32.vcxproj]

解决办法: 调换一下头文件的包含次序

#include <windows.h>
#include "./lib/glut.h"

改成:

#include "./lib/glut.h"
#include <windows.h>

……

错误太多,配置太困难,还是使用VS吧。

显示评论