Cmake使用方法

Cmake使用方法

  • 自定义输出目录
定义so库保存位置
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/lib)
定义a库保存位置
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/lib)
定义执行文件保存位置
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin)
  • 静态库与动态库同名存在
将cqueue_static指定输出为cqueue
set_target_properties(cqueue_static PROPERTIES OUTPUT_NAME "cqueue")
使动态库和静态库同时存在
set_target_properties(cqueue PROPERTIES CLEAN_DIRECT_OUTPUT 1)
set_target_properties(cqueue_static PROPERTIES CLEAN_DIRECT_OUTPUT 1)
  • 生成动态库版本
# 指定动态库版本
# VERSION 动态库版本
# SOVERSION API版本
set_target_properties(cqueue PROPERTIES VERSION 1.0 SOVERSION 1)
  • 获取文件夹下所有文件
aux_source_directory(. srcs)
  • 找不到pthread_create
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread -lpthread")
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread -lpthread")
有些编译器需要使用-pthread有些需要-lpthread
  • 获取编译时间
string(TIMESTAMP COMPILE_TIME %Y%m%d_%H%M%S)
add_definitions( -DCOMPILE_TIME=\"${COMPILE_TIME}\")
  • 获取编译git版本
# 添加自定义cmake文件目录
list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake)

# 使用Utility.cmake
include(Utility)

# 获取当前的GIT_HASH
set(GIT_HASH "unknown")
get_git_hash(GIT_HASH)
message(STATUS "Git hash is ${GIT_HASH}")

# 获取当前的分支
set(GIT_BRANCH "unknown")
get_git_branch(GIT_BRANCH)
  • 获取git信息make文件Utility.cmake
# get git hash
macro(get_git_hash _git_hash)
    find_package(Git QUIET)
    if(GIT_FOUND)
      execute_process(
        COMMAND ${GIT_EXECUTABLE} log -1 --pretty=format:%h
        OUTPUT_VARIABLE ${_git_hash}
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET
        WORKING_DIRECTORY
          ${CMAKE_CURRENT_SOURCE_DIR}
        )
    endif()
endmacro()

# get git branch
macro(get_git_branch _git_branch)
    find_package(Git QUIET)
    if(GIT_FOUND)
      execute_process(
        COMMAND ${GIT_EXECUTABLE} symbolic-ref --short -q HEAD
        OUTPUT_VARIABLE ${_git_branch}
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET
        WORKING_DIRECTORY
          ${CMAKE_CURRENT_SOURCE_DIR}
        )
    endif()
endmacro()

未完待续…

你可能感兴趣的:(Cmake,cmake,git)