CMakeConanNinja

conan库管理工具

pip3 install conan  //安装conan管理c++

配置conanfile.txt文件

[requires]
zlib/1.2.11@conan/stable

[generators]
cmake

引用自动生成的编译文件

include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()

链接依懒库

target_link_libraries(target ${CONAN_LIBS})

conan命令

conan search poco --remote=conancenter	#在远程查找搜索poco库所有的版本
conan remote list	#列出远程地址
conan remote add url	#添加远程有效的地址
conan remote remove url 	#移除远程地址

ninja

https://blog.jfz.me/2020/ninja.html

ninja支持如下参数:

--version  # 打印版本信息
-v         # 显示构建中的所有命令行(这个对实际构建的命令核对非常有用)

-C DIR     # 在执行操作之前,切换到`DIR`目录
-f FILE    # 制定`FILE`为构建输入文件。默认文件为当前目录下的`build.ninja`。如 ./ninja -f demo.ninja

-j N       # 并行执行 N 个作业。默认N=3(需要对应的CPU支持)。如 ./ninja -j 2 all
-k N       # 持续构建直到N个作业失败为止。默认N=1
-l N       # 如果平均负载大于N,不启动新的作业
-n         # 排练(dry run)(不执行命令,视其成功执行。如 ./ninja -n -t clean)

-d MODE    # 开启调试模式 (用 -d list 罗列所有的模式)
-t TOOL    # 执行一个子工具(用 -t list 罗列所有子命令工具)。如 ./ninja -t query all
-w FLAG    # 控制告警级别

cmake

函数

project

项目名称

set

设置变量

  • 设定编译输出目录
    set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/bin");

target_include_directories

新的引入头文件目录,旧的include _directories听说已经过时,但还可以使用。

include_directories

include_directories([AFTER|BEFORE] [SYSTEM] dir1 [dir2 ...])

添加头文件include目录到当前CMakeLists(包括build和target)。默认是目录的递归,相对目录是相对当前路径的。

install

安装编译文件

aux_source_directory

查找指定目录下源文件,该目录下的所有源文件

aux_source_directory(./ SRC)

add_libray

add_library(<name> [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] source1 [source2 ...])

增加一个叫name的链接库,可以选择是STATIC、SHARED或者是MODULE类型的。

  • STATIC:静态链接库,当生成可执行程序时进行链接。在Linux下为.a文件
  • SHARED:动态链接库,可执行程序运行时动态加载并链接。在Linux下为.so文件
  • MODULE:模块,可执行程序运行时动态加载,但不链接到可执行程序中。
    BUILD_SHARED_LIBS变量决定了默认值,如果为on则为动态的,否则为静态的
    可以通过设置CMAKE_LIBRARY_OUTPUT_DIRECTORY变量指定输出的路径
SET(LIBHELLO_SRC hello.c)
ADD_LIBRARY(hello SHARED ${LIBHELLO_SRC})       #添加动态库
#ADD_LIBRARY(hello STATIC ${LIBHELLO_SRC})      #添加静态库
#ADD_LIBRARY(hello_static STATIC ${LIBHELLO_SRC})  

生成库文件。

  • SHARED为生成动态库。
  • STATIC生成为静态库。
  • MODULE在使用 dyld 的系统有效,如果不支持 dyld,则被当作 SHARED 对待。

fileName为生成的文件名。${SRC}为源文件路径。

add_soubdirectory

添加项目子目录

add_soubdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL])
  • source_dir:首先需要指出另外这个CMakeLists的目录,可以使用相对路径(相对当前路径)和绝对路径。
  • binary_dir:接着指明编译生成二进制的目录,可以使用相对路径(相对当前路径)和绝对路径。目标目录是可选项,如不指定,目标文件会被放到source_dir
  • EXCLUDE_FROM_ALL:source_dir生成的目标会被排除在原目录的ALL target之外,也会排除在其IDE工程文件之外。比如source_dir是一些examples,原目录其实是不需要它们的,只是希望他们能编译,就可以添加这个命令。
//例子
add_subdirectory(../dlib dlib_build)

注意:当运行到该命令时,会立即跳到source_dir执行CMake,等到该CMakeLists执行完毕再跳回原来的CMakeLists执行add_subdirectory后面的命令。

add_compile_options

设置编译选项,也可以通过set命令修改CMAKE_CXX_FLAGS或CMAKE_C_FLAGS进行针对C和C++分别设置。但add_compile_options命令添加的编译选项是针对所有编译器的包括C/C加加。

add_compile_options(<option> ...)
# 例子
add_compile_options(-Wall -Wextra -pedantic -Werror -g)
#判断编译器类型,如果是gcc编译器,则在编译选项中加入c++11支持
if(CMAKE_COMPILER_IS_GNUCXX)
    set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
    message(STATUS "optional:-std=c++11")
endif(CMAKE_COMPILER_IS_GNUCXX)
link_directories(directory1 directory2 ...) 
#可以引入多个目录
#例子如下:
link_directories(${CMAKE_SOURCE_DIR}/thirdParty/glfw3/lib)

一般与target_link_libraries一起使用,先导入目录然后连接目标库文件。

添加需要链接的库文件目录,必须在add_executable前才有效,否则你会一直找不到要连接库的目录。

find_library

查找库所在目录,

find_library(GLFW3_LIB glfw3 ${CMAKE_SOURCE_DIR}/thirdParty/glfw3/lib NO_DEFAULT_PATH) #查找glfw3库,并指定变量为GLFw3_LIB,如果没找到就赋于NO_DEFAULT_PATH
link_libraries(${GLFW3_LIB}) 
  1. 第一个参数为变量
  2. 第二个参数为需要查找的库名称
  3. 查找的路径
  4. 如果没有找到被赋于变量

find_package

find_package(<package> [version] [EXACT] [QUIET] [MODULE] [REQUIRED] [[COMPONENTS] [components...]] [OPTIONAL_COMPONENTS components...] [NO_POLICY_SCOPE])

查找并加载外部工程,这个命令后,一个<package>_FOUND的变量会表明是否找到。
QUIET选项忽视找不到的消息;REQUIRED选项表明该外部包是必须的,找不到会立刻停止;
例子(这里的判断是没必要的,只是为了说明,因为找不到就会退出):

例子1

find_package(OpenCV REQUIRED)
if (OpenCV_FOUND)
  include_directories(${OpenCV_INCLUDE_DIRS})
else()
  message("OpenCV not found, so we won't build the project.")
endif()

例子2

find_package(glfw3 required)    #参数1是来自glfw3-config.cmake前面的glfw3,参数2:指定该文件是否必须找到否则解析报错。

报错找不到 glfw3,因为安装位置不在系统默认路径下。
让find_package 到指定路径找包,有三种方法:

  1. 设置 DIR
set(glfw3_DIR /glfw-3.3.8)
find_package(glfw3 required)
  1. 设置 PATHS
set(glfw3 required PATHS ~/glfw-3.3.8)
  1. cmake 时,指定 DCMAKE_PREFIX_PATH
cmake -DCMAKE_PREFIX_PATH="~/glfw-3.3.8" ..
#或者
set(CMAKE_PREFIX_PATH "./glfw-3.3.8")

添加需要链接的库文件路径,可指定多个链接文件,在add_executable之前使用,在新版cmake本中不建意使用。

    find_library(GLFW3_LIB glfw3 ${CMAKE_SOURCE_DIR}/thirdParty/glfw3/lib NO_DEFAULT_PATH)
    link_libraries(${GLFW3_LIB})    #连接使用find_library找到的库

一般和find_library一起使用,连接找到的库文件。

target_include_directories

# 指定 ${PROJECT_NAME}, 也就是 HelloCMake 的头文件搜索路径
target_include_directories( ${PROJECT_NAME}         # 参数1 项目名称
    PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include     # 参数2, 指定哪个搜索头文件路径, 这里的PRIVATE是cmake内置系统关键字,属性传递有3个: PRIVATE, PUBLIC 和 INTERFACE。
)

target_include_directories 用于解决代码中使用 #include<头文件>,编译器无法找到头文件的问题。它的作用就是告诉编译器,应该去哪个目录下搜索头文件。

使用 target_include_directories 需要创建项目后再使用,也就是位于 add_library和 add_executable之后使用,否则不会生效。 因为target_include_directories的第一个参数需要指定目标。

...
add_library( 项目A ...) # add_executable(...)
...
target_include_directories( ${PROJECT_NAME}        
    PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include     # 路径1
    PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src    		# 路径2
    PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}     		# 路径3
)

target_include_directories 的作用,用于给固定目标指定头文件搜索路径。与之对应的是 include_directories。include_directories也是用于设置头文件搜索路径。

名称 区别
target_include_directories 为指定的目标设置头文件搜索路径设置
include_directories 为当前CMakeLists.txt中的项目设定头文件搜索路径设置
  • 也就是说,CMakeLists.txt脚本中,可创建多个项目
    • 当使用target_include_directories时,只能为某一个项目设置头文件设置
    • 当使用include_directories时,当前脚本文件中的所有项目都会使用include_directories参数中的路径。 具有传递性。

使用注意:

  • 如果你的CMakeLists.txt脚本中只有单个项目, 那么, target_include_directories 和 include_directories的效果是一样的
  • 如果CMakeLists.txt脚本中存在多个项目,建议使用target_include_directories,避免某些项目引用到其他用不到的目录而引发的问题。
  • Modern CMake中 支持 target_include_directories 用法。
  • 简明扼要
    • include_directories: 1 VS 多
    • target_include_directories: 1 VS 1
  1. include_directories具有传递性:会为子目录中的项目增加头文件路径的设置。
  2. target_include_directories:
  • target_include_directories 的作用是为具体的目标设置 INCLUDE_DIRECTORIES 和 INTERFACE_INCLUDE_DIRECTORIES 属性。
  • PRIVATE 和 PUBLIC 关键字是用来设定目标的 INCLUDE_DIRECTORIES属性
  • INTERFACE 和 PUBLIC 关键字是用来设定目标的 INTERFACE_INCLUDE_DIRECTORIES属性
  • 区别:
    • PRIVATE: 仅当前目标使用,不会将 PRIVATE后 紧跟的参数进行传递
    • PUBLIC: PUBLIC 后面紧跟的参数, 自己使用外, 也传递给给别人使用
    • INTERFACE: INTERFACE 后面紧跟的参数,自己不用,传递给别人使用

设置要链接的库文件的名称

#连接到debug版本库
target_link_libraries(${PROJECT_NAME} PRIVATE debug ${LIBRARY})
#连接到release版本库
target_link_libraries(${PROJECT_NAME} PRIVATE optimized ${LIBRARY})

在add_executable之后,一般配合link_directories一起使用,先引入要连接的目录,再连接目标

link_directories(${CMAKE_SOURCE_DIR}/thirdParty/glfw3/lib)
add_executable(${PROJECT_NAME} ${PROJECT_SRCS} ${SRCS})
target_link_libraries(${PROJECT_NAME} ${OPENGL_LIBRARIES} glfw3)

target_compile_definitions

add_executable

add_executable(apption)

为工程生成目标文件

add_definitions

add_definitions(-DNEPTUNE3D_LIBRARY)    #-D为必须,后面的NEPTUNE3D_LIBRARY为宏
add_definitions(-std=c++11) #如果用到了C++11特性,需要让CMake支持该特性

向工程文件中添加编译宏

configure_file

用于自定义编译选项

configure_file (
  "${PROJECT_SOURCE_DIR}/config.h.in"
  "${PROJECT_BINARY_DIR}/config.h"
  )

set_property

set_property(TARGET ${PROJECT_NAME} PROPERTY FOLDER "external")

option

option(<variable> "<help_text>" [value])
  • variable:定义选项名称
  • help_text:说明选项的含义
  • value:定义选项默认状态,一般是OFF或者ON,除去ON之外,其他所有值都为认为是OFF

file

有些资源文件或者配置文件需要从源文件目录移动到生成文件目录,这个时候可以使用file命令,file命令可以进行文件写入、读取、生成、下载、上传、重命名等操作,可以使用file命令包含指定文件并指定变量。

file(<COPY|INSTALL> <files>... DESTINATION <dir> [FILE_PERMISSIONS <permissions>...] [DIRECTORY_PERMISSIONS <permissions>...] [NO_SOURCE_PERMISSIONS] [USE_SOURCE_PERMISSIONS] [FILES_MATCHING] [[PATTERN <pattern> | REGEX <regex>] [EXCLUDE] [PERMISSIONS <permissions>...]] [...])

基本操作如下:

FILE(WRITEfilename "message to write"... )
FILE(APPENDfilename "message to write"... )
FILE(READfilename variable)
FILE(GLOBvariable [RELATIVE path] [globbing expression_r_rs]...)
FILE(GLOB_RECURSEvariable [RELATIVE path] [globbing expression_r_rs]...)
FILE(REMOVE[directory]...)
FILE(REMOVE_RECURSE[directory]...)
FILE(MAKE_DIRECTORY[directory]...)
FILE(RELATIVE_PATHvariable directory file)
FILE(TO_CMAKE_PATHpath result)
FILE(TO_NATIVE_PATHpath result)

COPY一个<files>(文件、目录或者链接)到一个目标位置DESTINATION <dir>。如果使用相对路径,<files>将会是相对当前源文件目录,而<dir>将会是相对当前build目录。复制默认使用USE_SOURCE_PERMISSIONS选项,即保留源文件权限,包括可执行性等,可以通过显式声明NO_SOURCE_PERMISSIONS来去除。
实例:

file(COPY ./dlib/data/ DESTINATION ./dlib_models)

这样子就可以将源文件目录下的一些模型(data文件夹内所有)复制到生成二进制文件的dlib_models目录了。

file(GLOB PROJECT_SRCS ./thirdParty/glad/src/glad.c)
add_executable(${PROJECT_NAME} ${PROJECT_SRCS} ${SRCS})
#查找指定文件夹下所有*.cpp文件并添加到mains变量中
file(GLOB_RECURSE mains RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_FILE}")
foreach(mainfile IN LISTS mains)
    # Get file name without directory
    get_filename_component(fileName ${mainfile} NAME_WE)
    add_executable(${fileName} ${mainfile} ${THIRDPARTY_SRCS})
endforeach()

message

输出消息

message("No GUI support, so we won't build the ${name} example.")  #name是一个变量

流程条件语句

if

if (DLIB_NO_GUI_SUPPORT)
    message("No GUI support, so we won't build the ${name} example.")
else()
    add_example(${name})
endif()

关系操作符

关系操作符 说明
NOT 非,NOT E1
AND 与,E1 AND E2
OR 或,E1 OR E2
EXIST ~ E,存在 name 的文件或者目录(应该使用绝对路径),真
COMMAND ~ E,存在 command-name 命令、宏或函数且能够被调用,真
DEFINED ~ E,变量被定义了,真
EQUAL E1 ~ E2,变量值或者字符串匹配 regex 正则表达式
LESS
GREATER
STRLESS E1 ~ E2,变量值或者字符串为有效的数字且满足小于(大于、等于)的条件
STRGREATER
STREQUAL

例子:

if(WIN32)	#如果是WIN32系统
	set(CMAKE_DEBUG_POSTFIX "d")  
    if(MSVC)        
    	include(ChooseMSVCCRT.cmake) 
    endif(MSVC)
    add_definitions(-DGLSLANG_OSINCLUDE_WIN32)
elseif(UNIX) #如果是unix系统
	add_definitions(-DGLSLANG_OSINCLUDE_UNIX)
elseif (APPLE)	#apple系统
	message("apple platform")
else(WIN32)    
	message("unknown platform")
endif(WIN32)	#退出条件
if (DEFINED MSVC_VERSION) 
	if (MSVC_VERSION GREATER_EQUAL 1500) 
		set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++14")
	endif()    
	if (MSVC_VERSION GREATER_EQUAL 1910)   
		set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /permissive-")  
	endif()
endif()

内置变量

设置内部变量有两种方式,一种是直接在cmake命令后面加-D+命令+=+值,如cmake .. -DBUILD_SHARED_LIBS=OFF。第二种是在CMakeLists文件中使用set命令,如set(BUILD_SHARED_LIBS OFF)

BUILD_SHARED_LIBS

Switch between shared and static libraries

CMAKE_CXX_STANDARD_REQUIRED

CMAKE_CREATE_WIN32_EXE

CMAKE_SOURCE_DIR

代表工程的根目录,也就是最上层目录

CMAKE_RUNTIME_OUTPUT_DIRECTORY

设置可执行文件的输出目录。

CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG

设置Debug版本可执行文件输出目录

CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE

设置Release版本可执行文件输出目录

CMAKE_BUILD_TYPE

在cmakelists.txt文件中指定编译类型.

set(CMAKE_BUILD_TYPE "release") #指定编译为release版本
set(CMAKE_BUILD_TYPE "debug")   #指定编译为debug版本

CMAKE_CCOMPILER

指定c编译器

CMAKE_CXX_COMPILER

CMAKE_C_FLAGS

编译C文件时的选项,如-g;也可以通过add_definitions添加编译选项。

CMAKE_CXX_STANDARD

set(CMAKE_CXX_STANDARD 14)  //使用c++14

使用cxx的标准版本号也可以通过下面语句来设定.

add_definitions(-std=c++14)

CMAKE_RUNTIME_OUTPUT_DIRECTORY_

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${PROJECT_SOURCE_DIR}/../bin) 
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${PROJECT_SOURCE_DIR}/../bin) 

上面两条语句分别设置了Debug版本和Release版本可执行文件的输出目录,

一旦设置上面的属性,在任何环境下生成的可执行文件都将直接放在你所设置的目录.

CMAKE_ARCHIVE_OUTPUT_DIRECTORY_

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${PROJECT_SOURCE_DIR}/../lib)    set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${PROJECT_SOURCE_DIR}/../lib) 

上面两条语句分别设置了Debug版本和Release版本生成动态库或静态库文件的输出目录,

一旦设置上面的属性,在任何环境下生成的库文件都将直接放在你所设置的目录.

一定要放在add_library前才起作用。

# 设置 可执行程序输出目录
set(publish_bin_debug 			${CMAKE_CURRENT_SOURCE_DIR}/publish/${platform_info}/bin/debug)
set(publish_bin_release 		${CMAKE_CURRENT_SOURCE_DIR}/publish/${platform_info}/bin/release)

# 设置库文件输出目录
set(publish_lib_debug 			${CMAKE_CURRENT_SOURCE_DIR}/publish/${platform_info}/lib/debug)
set(publish_lib_release 		${CMAKE_CURRENT_SOURCE_DIR}/publish/${platform_info}/lib/release)


# 指定可执行程序输出目录
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG 	${publish_bin_debug})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE 	${publish_bin_release})

# 指定 库文件输出目录
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG 	${publish_lib_debug})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RLEASE 	${publish_lib_release})

CMAKE_DEBUG_POSTFIX

    set(CMAKE_DEBUG_POSTFIX "_d")

上面两条语句分别设置了Debug版本下库文件的后缀名.

CMAKE_RELEASE_POSTFIX

    set(CMAKE_RELEASE_POSTFIX "_r") 

上面两条语句分别设置了Release版本下库文件的后缀名.

CAMEK_PREFIX_PATH

set(CAMEK_PREFIX_PATH "./cmake")

搜索库文件的XXX-config.cmake文件路径。必须在使用find_package前设置此变量。

CMAKE_COMPILER_IS_GNUCXX

编译器是否是gcc

    #判断编译器类型,如果是gcc编译器,则在编译选项中加入c++11支持
    if(CMAKE_COMPILER_IS_GNUCXX)
        set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
        message(STATUS "optional:-std=c++11")   
    endif(CMAKE_COMPILER_IS_GNUCXX)

CMAKE_SOURCE_DIR

构建源码顶层路径

CMAKE_BINARY_DIR

编译输出目录的顶层路径

CMAKE_CURRENT_SOURCE_DIR

指的是当前处理的 CMakeLists.txt 所在的路径,比如上面我们提到的 src 子目录。

CMAKE_CURRENT_BINARY_DIR

当前编译目录

CMAKE_INSTALL_PREFIX

指定安装目录

DEBUG_POSTFIX

set(CMAKE_DEBUG_POSTFIX _d) #在编译输出文件名后加_d

此命令与上MAKE_DEBUG_POSTFIX效果相同。

EXECUTABLE_OUTPUT_PATH

可执行文件的存放路径

SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/../bin) 

上面的语句能设置可执行文件的输出目录

在Win + VS环境下,会自动在你所设置的目录后面扩展一层 <CONFIG> 目录,所以最终生成的Debug版本程序会在 ${PROJECT_SOURCE_DIR}/../bin/Debug 目录下,Release版本程序会在 $/../bin/Release 目录下.

在Linux + GCC环境下,无论是Debug还是Release,生成的可执行程序会直接放在你所设置的目录下,不会有差异.

PROJECT_NAME

项目名称,对应project中的值。

PROJECT_SOURCE_DIR

由project命令生成,指向CMakeLists目录绝对路径。

PROJECT_BINARY_DIR

由project命令生成,指向build目录的绝对路径

PROPERTIES DEBUG_POSTFIX

set_target_properties(${TARGET_NAME} PROPERTIES DEBUG_POSTFIX "_d")
set_target_properties(${TARGET_NAME} PROPERTIES RELEASE_POSTFIX "_r") 

上面两条语句分别设置了Debug版本和Release版本下可执行文件的后缀名.

LIBRARY_OUTPUT_PATH

设置编译库输出的目录

SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/../lib) 

上面的语句能设置库文件的输出目录

在Win + VS环境下,会自动在你所设置的目录后面扩展一层 <CONFIG> 目录,所以最终生成的Debug版本库会在 ${PROJECT_SOURCE_DIR}/../lib/Debug 目录下,Release版本库会在 $/../lib/Release 目录下.

在Linux + GCC环境下,无论是Debug还是Release,生成的库文件会直接放在你所设置的目录下,不会有差异.

CMAKE_CL_64

CMAKE_HOST_SYSTEM_NAME

当前所用操作系统名称

CMAKE_SYSTEM_NAME

CMAKE_HOST_UNIX

CMAKE_HOST_WIN32

CMAKE_SYSTEM_VERSION

APPLE

MSVC

MINGW

MSYS

protobuf for cmake

详细相关文档:FindProtobuf — CMake 3.27.0-rc3 Documentation

变量

  • Protobuf_INCLUDE_DIRS
    包括Google Protocol Buffers的目录
  • Protobuf_LIBRARIES
    搜索连接的protobuf库位置
  • Protobuf_LITE_LIBRARIES
    protobuf协议库

Qt宏

CMAKE_AUTOUIC

set(CMAKE_AUTOUIC ON)

自动编译UI文件

CMAKE_AUTOMOC

set(CMAKE_AUTOMOC ON)

自动编译MOC文件

CMAKE_AUTORCC

set(CMAKE_AUTORCC ON)

自动编译RCC文件

例子一

cmake_minimum_required(VERSION 3.13)	#cmake版本
project(CodeBucket)		#项目名称

set(CMAKE_CXX_STANDARD 14)

#设置编译输出目标位置
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/cmake-build-debug/bin")
#使用SEt设置变量
set(GLFW_LINK ${THIRDPARTY}/openGL/glfw-3.2.1.bin.WIN64/lib-vc2015/glfw3.lib)
set(TBBMALLOC_LINK ${THIRDPARTY}/embree-3.5.2.x64.vc14.windows/lib/tbbmalloc.lib)

add_subdirectory(openGL)	#设置子项目
include_directories(${GLM_INCLUDE_DIR})		#包含头文件目录
link_libraries(${TBBMALLOC_LINK} ${GLEW_LINK})	#连接指定库文件
#如果是msvc编译器...
if(MSVC)
    set(CMAKE_CREATE_WIN32_EXE "/SUBSYSTEM:WINDOWS /ENTRY:\"mainCRTStartup\"")
endif(MSVC)

macro(宏)

macro(<name> [<arg1> ...])
  <commands>
endmacro()
macro(add_example name)	#定义宏
	project(${name})   #项目名
	set(_Example_Sources ${ARGN}) 
	source_group("" FILES ${_Example_Sources})
	source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${_Example_Sources}) 
    
	set(_Example_Type)    
	if (WIN32)
		set(_Example_Type WIN32) 
        
		set(ApplicationIcon ${CMAKE_SOURCE_DIR}/Examples/Common/Support/Icon.ico)
		file(TO_NATIVE_PATH "${ApplicationIcon}" ApplicationIcon)       
		string(REPLACE "\\" "\\\\" ApplicationIcon "${ApplicationIcon}")        
		configure_file(
			${CMAKE_SOURCE_DIR}/Examples/Common/Support/Resource.rc.in     									${CMAKE_CURRENT_BINARY_DIR}/Resource.rc)        
		set(_Example_Resources ${CMAKE_CURRENT_BINARY_DIR}/Resource.rc)
	elseif (APPLE)
    	set(_Example_Type MACOSX_BUNDLE)
    	
    	file(GLOB _Example_Resources "${CMAKE_SOURCE_DIR}/Data/*") 
      	set_source_files_properties(${_Example_Resources} PROPERTIES 
        	MACOSX_PACKAGE_LOCATION "Resources/Data")        
        set(_Example_Icon "${CMAKE_SOURCE_DIR}/Examples/Common/Support/Icon.icns")
        list(APPEND _Example_Resources ${_Example_Icon})   
        set_source_files_properties(${_Example_Icon} PROPERTIES 
        	MACOSX_PACKAGE_LOCATION "Resources")    
    endif()    
    add_executable(${name} ${_Example_Type} ${_Example_Sources} ${_Example_Resources}) 
    
    find_package(imgui REQUIRED)    
    find_package(imgui_node_editor REQUIRED)    
    target_link_libraries(${name} PRIVATE imgui imgui_node_editor Application)  
    
    set(_ExampleBinDir ${CMAKE_BINARY_DIR}/Bin)  
    
    set_target_properties(${name} PROPERTIES       
   		FOLDER "Examples"
    	RUNTIME_OUTPUT_DIRECTORY                "${_ExampleBinDir}"        
    	RUNTIME_OUTPUT_DIRECTORY_DEBUG          "${_ExampleBinDir}"     
    	RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${_ExampleBinDir}"   
    	RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL     "${_ExampleBinDir}"        	
    	RUNTIME_OUTPUT_DIRECTORY_RELEASE        "${_ExampleBinDir}"    
    	DEBUG_POSTFIX                           _d      
    	RELWITHDEBINGO_POSTFIX                  _rd      
    	MINSIZEREL_POSTFIX                      _r      
    	VS_DEBUGGER_WORKING_DIRECTORY           ${_ExampleBinDir}      
    	MACOSX_BUNDLE_INFO_PLIST         "${CMAKE_SOURCE_DIR}/Examples/Common/Support/Info.plist.in" 
   	 	MACOSX_BUNDLE_BUNDLE_NAME               "${PACKAGE_NAME}"      
    	MACOSX_BUNDLE_GUI_IDENTIFIER            "com.sandbox.collisions"       
    	MACOSX_BUNDLE_LONG_VERSION_STRING       "${PACKAGE_VERSION}"    
    	MACOSX_BUNDLE_SHORT_VERSION_STRING      "${PACKAGE_VERSION_MAJOR}.${PACKAGE_VERSION_MINOR}"  
    	MACOSX_BUNDLE_ICON_FILE                 Icon.icns 
        )  
    add_custom_command(
    	TARGET ${name} 
    	PRE_BUILD        
    	COMMAND ${CMAKE_COMMAND} -E make_directory ARGS ${_ExampleBinDir}        
    	COMMAND ${CMAKE_COMMAND} -E copy_directory ARGS ${CMAKE_SOURCE_DIR}/Data {_ExampleBinDir}/Data)
    endmacro()	#退出宏定义

function(函数)

function(<name> [<arg1> ...])
  <commands>
endfunction()

function可结合return()使用,也就是说,函数体可以写return()。

function(func_demo)
    message("hello")
    return()    #在此处已返回
    mressage("world")   #上面已经return此句不再执行。
endfunction()
function(glslang_set_link_args TARGET)
    # For MinGW compiles, statically link against the GCC and C++ runtimes.
    # This avoids the need to ship those runtimes as DLLs.
    if(WIN32 AND ${CMAKE_CXX_COMPILER_ID} MATCHES "GNU")
        set_target_properties(${TARGET} PROPERTIES
                              LINK_FLAGS "-static -static-libgcc -static-libstdc++")
    endif()
endfunction(glslang_set_link_args)

set(src ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
add_excutable(helloworld ${src})		#编译的文件列表

CMAKE设置调试

    set(CMAKE_BUILD_TYPE "debug")
    set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g2 -ggdb")

判断是否64位编译

# 64位
if (CMAKE_CL_64)
	set(platform_info x64)
# 86
else()
	set(platform_info x86)
endif()
#可以用${platform_info}进行设置x64或x86

更改windows sdk版本

cmake -DCMAKE_SYSTEM_VERSION=10.0.17763.0

Command

>cmake -h

Usage

  cmake [options] <path-to-source>
  cmake [options] <path-to-existing-build>
  cmake [options] -S <path-to-source> -B <path-to-build>

Specify a source directory to (re-)generate a build system for it in the
current working directory.  Specify an existing build directory to
re-generate its build system.

Options
  -S <path-to-source>          = Explicitly specify a source directory.
  -B <path-to-build>           = Explicitly specify a build directory.
  -C <initial-cache>           = Pre-load a script to populate the cache.
  -D <var>[:<type>]=<value>    = Create or update a cmake cache entry.
  -U <globbing_expr>           = Remove matching entries from CMake cache.
  -G <generator-name>          = Specify a build system generator.
  -T <toolset-name>            = Specify toolset name if supported by
                                 generator.
  -A <platform-name>           = Specify platform name if supported by
                                 generator.
  -Wdev                        = Enable developer warnings.
  -Wno-dev                     = Suppress developer warnings.
  -Werror=dev                  = Make developer warnings errors.
  -Wno-error=dev               = Make developer warnings not errors.
  -Wdeprecated                 = Enable deprecation warnings.
  -Wno-deprecated              = Suppress deprecation warnings.
  -Werror=deprecated           = Make deprecated macro and function warnings
                                 errors.
  -Wno-error=deprecated        = Make deprecated macro and function warnings
                                 not errors.
  -E                           = CMake command mode.
  -L[A][H]                     = List non-advanced cached variables.
  --build <dir>                = Build a CMake-generated project binary tree.
  --install <dir>              = Install a CMake-generated project binary
                                 tree.
  --open <dir>                 = Open generated project in the associated
                                 application.
  -N                           = View mode only.
  -P <file>                    = Process script mode.
  --find-package               = Run in pkg-config like mode.
  --graphviz=[file]            = Generate graphviz of dependencies, see
                                 CMakeGraphVizOptions.cmake for more.
  --system-information [file]  = Dump information about this system.
  --log-level=<ERROR|WARNING|NOTICE|STATUS|VERBOSE|DEBUG|TRACE>
                               = Set the verbosity of messages from CMake
                                 files.  --loglevel is also accepted for
                                 backward compatibility reasons.
  --log-context                = Prepend log messages with context, if given
  --debug-trycompile           = Do not delete the try_compile build tree.
                                 Only useful on one try_compile at a time.
  --debug-output               = Put cmake in a debug mode.
  --debug-find                 = Put cmake find in a debug mode.
  --trace                      = Put cmake in trace mode.
  --trace-expand               = Put cmake in trace mode with variable
                                 expansion.
  --trace-format=<human|json-v1>
                               = Set the output format of the trace.
  --trace-source=<file>        = Trace only this CMake file/module.  Multiple
                                 options allowed.
  --trace-redirect=<file>      = Redirect trace output to a file instead of
                                 stderr.
  --warn-uninitialized         = Warn about uninitialized values.
  --warn-unused-vars           = Warn about unused variables.
  --no-warn-unused-cli         = Don't warn about command line options.
  --check-system-vars          = Find problems with variable usage in system
                                 files.
  --profiling-format=<fmt>     = Output data for profiling CMake scripts.
  --profiling-output=<file>    = Select an output path for the profiling data
                                 enabled through --profiling-format.
  --help,-help,-usage,-h,-H,/? = Print usage information and exit.
  --version,-version,/V [<f>]  = Print version number and exit.
  --help-full [<f>]            = Print all help manuals and exit.
  --help-manual <man> [<f>]    = Print one help manual and exit.
  --help-manual-list [<f>]     = List help manuals available and exit.
  --help-command <cmd> [<f>]   = Print help for one command and exit.
  --help-command-list [<f>]    = List commands with help available and exit.
  --help-commands [<f>]        = Print cmake-commands manual and exit.
  --help-module <mod> [<f>]    = Print help for one module and exit.
  --help-module-list [<f>]     = List modules with help available and exit.
  --help-modules [<f>]         = Print cmake-modules manual and exit.
  --help-policy <cmp> [<f>]    = Print help for one policy and exit.
  --help-policy-list [<f>]     = List policies with help available and exit.
  --help-policies [<f>]        = Print cmake-policies manual and exit.
  --help-property <prop> [<f>] = Print help for one property and exit.
  --help-property-list [<f>]   = List properties with help available and
                                 exit.
  --help-properties [<f>]      = Print cmake-properties manual and exit.
  --help-variable var [<f>]    = Print help for one variable and exit.
  --help-variable-list [<f>]   = List variables with help available and exit.
  --help-variables [<f>]       = Print cmake-variables manual and exit.

Generators

The following generators are available on this platform (* marks default):
  Visual Studio 16 2019        = Generates Visual Studio 2019 project files.
                                 Use -A option to specify architecture.
* Visual Studio 15 2017 [arch] = Generates Visual Studio 2017 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Visual Studio 9 2008 [arch]  = Generates Visual Studio 2008 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Borland Makefiles            = Generates Borland makefiles.
  NMake Makefiles              = Generates NMake makefiles.
  NMake Makefiles JOM          = Generates JOM makefiles.
  MSYS Makefiles               = Generates MSYS makefiles.
  MinGW Makefiles              = Generates a make file for use with
                                 mingw32-make.
  Unix Makefiles               = Generates standard UNIX makefiles.
  Green Hills MULTI            = Generates Green Hills MULTI files
                                 (experimental, work-in-progress).
  Ninja                        = Generates build.ninja files.
  Ninja Multi-Config           = Generates build-<Config>.ninja files.
  Watcom WMake                 = Generates Watcom WMake makefiles.
  CodeBlocks - MinGW Makefiles = Generates CodeBlocks project files.
  CodeBlocks - NMake Makefiles = Generates CodeBlocks project files.
  CodeBlocks - NMake Makefiles JOM
                               = Generates CodeBlocks project files.
  CodeBlocks - Ninja           = Generates CodeBlocks project files.
  CodeBlocks - Unix Makefiles  = Generates CodeBlocks project files.
  CodeLite - MinGW Makefiles   = Generates CodeLite project files.
  CodeLite - NMake Makefiles   = Generates CodeLite project files.
  CodeLite - Ninja             = Generates CodeLite project files.
  CodeLite - Unix Makefiles    = Generates CodeLite project files.
  Sublime Text 2 - MinGW Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - NMake Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - Ninja       = Generates Sublime Text 2 project files.
  Sublime Text 2 - Unix Makefiles
                               = Generates Sublime Text 2 project files.
  Kate - MinGW Makefiles       = Generates Kate project files.
  Kate - NMake Makefiles       = Generates Kate project files.
  Kate - Ninja                 = Generates Kate project files.
  Kate - Unix Makefiles        = Generates Kate project files.
  Eclipse CDT4 - NMake Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - MinGW Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Ninja         = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files.
posted @   alvinlyb  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示