cmake如何使用
时间: 2023-07-18 21:12:11 浏览: 58
CMake是一个跨平台的开源构建工具,用于管理C++项目的构建过程。它可以自动生成Makefile、Visual Studio、Xcode等构建文件,并支持多种编译器,使得在不同平台上构建项目变得更加容易。
下面是简单的CMake使用步骤:
1. 编写CMakeLists.txt文件,定义项目名称、源文件、包含目录、库文件等信息。
2. 在命令行中进入项目目录,执行`cmake .`命令生成构建文件。
3. 执行构建文件,生成可执行文件或库文件。
具体操作步骤如下:
1. 编写CMakeLists.txt文件
CMakeLists.txt文件是CMake的配置文件,用于指定项目的属性和构建规则。以下是一个简单的CMakeLists.txt文件示例:
```
# 指定项目名称
project(hello)
# 指定最小版本号
cmake_minimum_required(VERSION 3.10)
# 添加源文件
add_executable(hello main.cpp)
# 添加头文件目录
include_directories(include)
# 添加库文件
target_link_libraries(hello libfoo.a)
```
上述示例指定了项目名称为`hello`,最小版本号为3.10,添加了一个源文件`main.cpp`,指定了头文件目录`include`,并链接了一个库文件`libfoo.a`。
2. 生成构建文件
在命令行中进入项目目录,执行`cmake .`命令生成构建文件。这个命令会根据CMakeLists.txt文件生成对应的Makefile、Visual Studio、Xcode等构建文件。
```
$ cmake .
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- 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: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- 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: /path/to/project
```
3. 执行构建文件
执行构建文件,生成可执行文件或库文件。这个命令会根据前面生成的构建文件进行编译、链接等操作。
```
$ make
Scanning dependencies of target hello
[ 50%] Building CXX object CMakeFiles/hello.dir/main.cpp.o
[100%] Linking CXX executable hello
[100%] Built target hello
```
以上就是CMake的基本使用方法,更多详细的用法可以参考CMake官方文档。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)