CMake 学习【三】—— 为自定义库添加使用要求

tech2024-07-07  57

1. 添加使用要求的四种命令

为了添加使用要求,常用下面四种命令:

1.1 target_compile_definitions()

添加编译定义:

target_compile_definitions(<target> <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])

其中 :

< target> 必须已经通过add_executable() 或者add_library() 创建,并且must not be an ALIAS target(输入工程).关键字INTERFACE,PUBLIC和PRIVATE用来指定其后参数的作用域。PRIVATE 和 PUBLIC 项将产生 的 COMPILE_DEFINITIONS 属性。PUBLIC 和 INTERFACE 项将产生 的INTERFACE_COMPILE_DEFINITIONS 属性。其后的参数指定编译定义。重复调用相同的目标将按照调用顺序追加(定义)。target_compile_definitions的参数可以使用带语法$<…>的“生成表达式”。关于有效的表达式可以查看cmake-generator-expressions(7)手册。关于更多的系统属性的定义可以查看cmake-buildsystem(7)助手。

例如下面的用法:

target_compile_definitions(foo PUBLIC FOO) target_compile_definitions(foo PUBLIC -DFOO) # -D removed target_compile_definitions(foo PUBLIC "" FOO) # "" ignored target_compile_definitions(foo PUBLIC -D FOO) # -D becomes "", then ignored

1.2 target_compile_options()

target_compile_options(<target> [BEFORE] <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])

If BEFORE is specified, the content will be prepended to the property instead of being appended.

The INTERFACE, PUBLIC and PRIVATE keywords are required to specify the scope of the following arguments. PRIVATE and PUBLIC items will populate the COMPILE_OPTIONS property of . PUBLIC and INTERFACE items will populate the INTERFACE_COMPILE_OPTIONS property of . (IMPORTED targets only support INTERFACE items.) The following arguments specify compile options. Repeated calls for the same append items in the order called.

Arguments to target_compile_options may use “generator expressions” with the syntax $<…>. See the cmake-generator-expressions(7) manual for available expressions. See the cmake-buildsystem(7) manual for more on defining buildsystem properties.

1.3 target_include_directories()

Specifies include directories to use when compiling a given target.

target_include_directories(<target> [SYSTEM] [BEFORE] <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])

1.4 target_link_libraries()

https://cmake.org/cmake/help/v3.18/command/target_link_libraries.html#command:target_link_libraries

2. 使用示例

在上一个例子中,我们在顶层的CMakelist中include了mathfunctions的路径,也就是mathfunction库函数内的CMakelists不需要包含。我们把这个就称为接口。 那么现在我们在库函数内的CMakeLIsts中添加接口定义的使用要求:

target_include_directories(MathFunctions INTERFACE ${CMAKE_CURRENT_SOURCE_DIR} )

那么现在我们就可以删掉顶层CMakeLists中的外部库函数路径声明:即以下内容可以删除:

if(USE_MYMATH) add_subdirectory(MathFunctions) list(APPEND EXTRA_LIBS MathFunctions) #list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")删除这行 endif() target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}" # ${EXTRA_INCLUDES}删除这样 )
最新回复(0)