菜鸟笔记
提升您的技术认知

CMake 配置编译类型

阅读 : 849

目录结构

├── cmakeLists.txt
└── main.c

源文件

main.c

#include <stdio.h>
int main(int argc, char *argv[])
{
  
    printf("build-type:cmake\r\n");
    return 0;
}

CMakeLists.txt

# Set the minimum version of CMake that can be used
# To find the cmake version run
# $ cmake --version
cmake_minimum_required(VERSION 3.5)

# Set a default build type if none was specified
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()

# Set the project name
project (build_type)

# Add an executable
add_executable(cmake_examples_build_type main.c)

编译

	$  mkdir build
	$  cd build/
	$  cmake .. -DCMAKE_BUILD_TYPE=Release
	$  make VERBOSE=1 (打印详细的编译信息)

说明

构建级别

Make具有许多内置的构建配置,可用于编译工程。 这些配置指定了代码优化的级别,以及调试信息是否包含在二进制文件中。

这些优化级别,主要有:

Release —— 不可以打断点调试,程序开发完成后发行使用的版本,占的体积小。 它对代码做了优化,因此速度会非常快,
在编译器中使用命令: -O3 -DNDEBUG 可选择此版本。
Debug ——调试的版本,体积大。
在编译器中使用命令: -g 可选择此版本。
MinSizeRel—— 最小体积版本
在编译器中使用命令:-Os -DNDEBUG可选择此版本。
RelWithDebInfo—— 既优化又能调试。
在编译器中使用命令:-O2 -g -DNDEBUG可选择此版本。

设置编译级别的方式

方式1:使用CMake图形界面
方式2:使用CMake命令行

cmake .. -DCMAKE_BUILD_TYPE=Release
cmake .. -DCMAKE_BUILD_TYPE=Debug