cmake 基本设置
2019-10-13 14:30 programming
一般可执行文件的设置
project(demo)
cmake_minimum_required(VERSION 3.0)
# 开启 make verbose 模式, 也可以用 `make VERBOSE=1`
set(CMAKE_VERBOSE_MAKEFILE ON)
# 指定编译器, 通常在编译时才指定.
#set(CMAKE_C_COMPILER /usr/bin/clang)
#set(CMAKE_CXX_COMPILER /usr/bin/clang++)
# 设置 c/c++ 版本, 可以考虑使用 c++14
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
# 默认使用 Release 模式, 只有显示指定 Debug 模式时才编译 debug 版本
set(CMAKE_CONFIGURATION_TYPES Debug Release)
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
# 分别设置 Debug 模式和 Release 模式不同的编译器选项
if (CMAKE_BUILD_TYPE MATCHES Debug)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -Wall -Werror -Wextra")
# -fno-rtti, Disable real-time type information
# -fno-exceptions Disable exceptions
# -fsanitize=address Enable memory sanitize plugin
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -Wall -Werror -Wextra -fno-exceptions")
# -fsanitize=address, Enable memory address sanitizer.
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")
# -fsanitize=leak, Enable memory leak sanitizer.
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=leak")
# -fsanitize=memory, Enable detecting uninitited memory sanitizer.
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=memory")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize-memory-track-origins \
-fPIC -pie -fno-omit-frame-pointer")
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wimplicit-fallthrough=1")
else()
# -Wl, -O2 Enable linker optimizations
#-Wl, --gc-sections Remove unused code resulting from -fdsta-sections and -ffunction-sections
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2 -Wl,-O1 -Wl,--gc-sections")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -O2 -Wl,-O1 -Wl,--gc-sections -Wno-unused-result")
endif()
# 修改 LD_LIBRARY_PATH, 编译时会把 `-Wl,-rpath,/tmp/add/lib` 传给编译器.
# 优先级比较高, 会先查找这样指定的目录, 再找系统目录.
LINK_DIRECTORIES(/tmp/add/lib)
# 编译时会把 `-I/tmp/add/include` 传给编译器. 优先级高.
INCLUDE_DIRECTORIES(/tmp/add/include)
add_executable(demo main.c)
target_link_libraries(demo add)
库的设置
以下以 libadd
为例:
project(add)
cmake_minimum_required(VERSION 3.0)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# 通常先定义一下库的版本号.
set(ADD_VERSION_MAJOR 0)
set(ADD_VERSION_MINOR 1)
set(ADD_VERSION_PATCH 3)
set(ADD_VERSION_STRING
${ADD_VERSION_MAJOR}.${ADD_VERSION_MINOR}.${ADD_VERSION_PATCH})
# 定义静态库
add_library(add_static STATIC add.c)
# 修改生成的 .a 文件的名称
set_target_properties(add_static PROPERTIES
OUTPUT_NAME "add")
# 定义动态库
add_library(add_shared SHARED add.c)
# 设置动态库的库文件名, 以及 so 版本号
# 这里可以不指定 public header, 而是单独为头文件创建一个 `install target`
set_target_properties(add_shared PROPERTIES
VERSION ${ADD_VERSION_STRING}
SOVERSION ${ADD_VERSION_MAJOR}
PUBLIC_HEADER add.h
OUTPUT_NAME "add")
# 设置动态库的安装目录
INSTALL(TARGETS add_shared
LIBRARY DESTINATION /tmp/add/lib
PUBLIC_HEADER DESTINATION /tmp/add/include)
# 设置静态库的安装目录
INSTALL(TARGETS add_static
DESTINATION /tmp/add/lib)