本文是 cmake 使用的第六篇。主要介绍如何设置编译器优化标志。
上一篇的链接为:https://blog.csdn.net/QCZL_CC/article/details/119825737,主要介绍如何将自己的软件安装到系统中。
目录结构如下:
05-build-type/
├── CMakeLists.txt
└── main.c
CMakeLists.txt 规则如下:
cmake_minimum_required(VERSION 3.5)
# CMake 提供的默认构建类型不包含用于优化的编译器标志。
# 对于某些项目,您可能希望设置默认构建类型,这样您就不必记住设置它。
# cmake 提供的级别有:
# Release - 添加 -O3 -DNDEBUG 标志
# Debug - 添加 -g 标志
# MinSizeRel - 添加 -Os -DNDEBUG
# RelWithDebInfo - 添加 -O2 -g -DNDEBUG 标志
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
message("Setting build type to 'RelWithDebInfo' as none was specified.")
set(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Choose the type of build." FORCE)
# Set the possible values of build type for cmake-gui
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release"
"MinSizeRel" "RelWithDebInfo")
endif()
project (build_type)
构建过程:
1:mkdir build 创建该目录的目的是为了将编译产物和源文件分离
2:cd build && cmake .. cmake 后面第一个参数应该是 CMakeLists.txt 文件所在目录。此实例中 CMakeLists.txt 在 build 目录的上一级,所以使用 cmake ..
3:make
使用 cmake .. 时未指定优化级别,则使用默认的 RelWithDebInfo 级别。日志如下:
qczl@DESKTOP-HP-ZHAN:build$ cmake ..
Setting build type to 'RelWithDebInfo' as none was specified.
-- 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: /home/qczl/cmake/01-basic/05-build-type/build
这样编译器编译时将使用 -O2 -g -DNDEBUG 级别优化代码。效果如下:
cmake .. -DCMAKE_BUILD_TYPE=Release 则可以自定义优化级别
qczl@DESKTOP-HP-ZHAN:build$ cmake .. -DCMAKE_BUILD_TYPE=Release
-- 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: /home/qczl/cmake/01-basic/05-build-type/build
这样编译器编译时将使用 -O3 -DNDEBUG 级别优化代码。效果如下:
下一篇:cmake 使用(七)_QCZL_CC的博客-CSDN博客,主要介绍如何设置编译标志,以便于在代码中使用预编译宏。