因为CMaked良好的跨平台特性,使用CMake越来越多,所以我们需要学习一下CMake语法

#设置CMake最小版本号
cmake_minimum_required (VERSION 3.18)  

#设置项目名称,项目语言,可以设置CXX, C, JAVA
#默认预定了两个变量 PROJECT_BINARY_DIR(系统预定),PROJECT_SOURCE_DIR(系统预定)
project(Test LANGUAGES CXX) 

#对于C++设置支持的版本,下面设置支持C++17
set(CMAKE_CXX_STANDARD 17)

#自定义全局宏变量
ADD_DEFINITIONS(-D_CONSOLE)

#设置项目头文件文件路径
include_directories(${PROJECT_SOURCE_DIR})
include_directories(${PROJECT_SOURCE_DIR}/include

#win下面判断编译器位数
#CMAKE_CL_64仅在windows上有效
IF(CMAKE_CL_64)
    set(platform x64)
ELSE(CMAKE_CL_64)
    set(platform x86)
ENDIF(CMAKE_CL_64)
#通过指针长度来判断
IF(CMAKE_SIZEOF_VOID_P EQUAL 8)
    set(platform x64)
ELSE()
    set(platform x86)
ENDIF()


#设置输出文件位置
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${PROJECT_SOURCE_DIR}/${platform}/bin_d)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${PROJECT_SOURCE_DIR}/${platform}/bin})


# 判断操作系统
MESSAGE (STATUS "current System : ${CMAKE_SYSTEM_NAME}")
IF (CMAKE_SYSTEM_NAME MATCHES "Linux")
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "Windows")
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
ELSE ()
MESSAGE(STATUS "other platform: ${CMAKE_SYSTEM_NAME}")
ENDIF (CMAKE_SYSTEM_NAME MATCHES "Linux")


IF (WIN32)
    MESSAGE(STATUS "Now is windows")
ELSEIF (APPLE)
    MESSAGE(STATUS "Now is Apple systens.")
ELSEIF (UNIX)
    MESSAGE(STATUS "Now is UNIX-like OS's. Including aPPLE os x  and CygWin")
ENDIF ()


## 判断编译器
MESSAGE (STATUS "current COMPILER : ${CMAKE_CXX_COMPILER_ID}")
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
# using Clang
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
# using GCC
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel")
# using Intel C++
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
# using Visual Studio C++
endif()

#判断编译选项,debug还是release
if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
  MESSAGE (STATUS "current is Debug mode")
  #SET (EXECUTABLE_OUTPUT_PATH /tmp/c/2019-09-12-cmaketest/test11/build/Debug)
endif()

if ("${CMAKE_BUILD_TYPE}" STREQUAL "Release")
  MESSAGE (STATUS "current is Release mode")
  #SET (EXECUTABLE_OUTPUT_PATH /tmp/c/2019-09-12-cmaketest/test11/build/Release)
endif()

#添加第三方库
#[1] 设置库头文件路径和库文件路径文件, xxxlib_INCLUDE 和xxxlib_LIBDIR 是自定义的变量,名字随便取
set(xxxlib_INCLUDE /Users/haoran/Downloads/wfdb/include)
set(xxxlib_LIBDIR /Users/haoran/Downloads/wfdb/lib)

#[2]
include_directories(${xxxlib_INCLUDE })   #添加头文件路径   
link_directories(${xxxlib_LIBDIR })       #添加库文件路径
target_link_libraries(test_boost xxx1 xxx2) #连接操作需要放到add_executable语句后面

#将各种文件归类到指定变量
#FILE(GLOB_RECURSE HEADERS "include/*.h")
#FILE(GLOB_RECURSE SOURCES "src/*.cpp") #使用 aux_source_directory(src SOURCES) 效果一样
#FILE(GLOB_RECURSE FORMS   "ui/*.ui")
#FILE(GLOB_RECURSE RESOURCE_FILES "*.qrc")
#FILE(GLOB TS_FILES "*.ts")

#set(SOURCES
#    ${SRC}/main.cpp
#    ${SRC}/xxx1.cpp
#    ${SRC}/xxx2.cpp)

#set(HEADER
#    ${INCLUDE}/xxx1.h
#    ${INCLUDE}/xxx2.h) 

# 将源代码添加到此项目的可执行文件。
add_executable (${PROJECT_NAME } ${SOURCES} ${HEADER})
最后编辑:2020年12月21日 ©著作权归作者所有

发表评论