Skip to content

Instantly share code, notes, and snippets.

@taogashi
Created December 29, 2016 12:44
Show Gist options
  • Save taogashi/33ebf6b4285ba96419b0aea3d7f4d63e to your computer and use it in GitHub Desktop.
Save taogashi/33ebf6b4285ba96419b0aea3d7f4d63e to your computer and use it in GitHub Desktop.
正确地使用ExternalProject_Add添加外部项目到本地cmake项目

官方文档
其中PREFIX决定了所有缺省的路径

TMP_DIR      = <prefix>/tmp
STAMP_DIR    = <prefix>/src/<name>-stamp
DOWNLOAD_DIR = <prefix>/src
SOURCE_DIR   = <prefix>/src/<name>
BINARY_DIR   = <prefix>/src/<name>-build
INSTALL_DIR  = <prefix>

其中INSTALL_DIR只会改变目标的properties里面属性,也就是可以用ExternalProject_Get_Property()获取 但并不会真的将外部项目的目标安装到那个目录, 想要制定外部项目目标文件安装路径,需要在传给外部项目的cmake参数中定义,即-DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> 才能真正生效。 当然,每一步的路径如果显式指定的话,是会覆盖prefix的路径的。 一般来说不用,特别是存放时间戳的文件夹不希望随意删除。

<prefix>/src/project_clockys-stamp文件夹下,存放了ExternalProject_Add的每一步的时间戳。 根据时间戳来确定某一步是否需要重新执行。如果把这些时间戳文件删掉,下一次编译就会从新下载源码, 并且将之前<prefix>下的文件全部删掉重来了,这不是我们所期望的。

ExternalProject_Add(project_libgp
PREFIX ${CMAKE_CURRENT_SOURCE_DIR}/external
GIT_REPOSITORY https://github.com/mblum/libgp.git
CMAKE_ARGS -DBUILD_TESTS=OFF -DBUILD_EXAMPLES=ON -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>)

ExternalProject_Get_Property(project_libgp install_dir)
add_library(gp STATIC IMPORTED)
set_target_properties(gp PROPERTIES
IMPORTED_LOCATION ${install_dir}/lib/libgp.a
INCLUDE_DIRECTORIES ${install_dir}/include)
add_dependencies(gp project_libgp)

并不是所有的项目都支持通过add_subdirectory的方式添加到当前项目。 上面用到的方法目前来说通用性更强。 用一个IMPORTED的库来维护外部项目的相关信息。 使用的时候,由于gp库不能传递头文件信息,只能通过get_target_property获取头文件路径 这样并不是很优雅。

get_target_property(LIBGP_INCLUDE_DIR gp INCLUDE_DIRECTORIES)

add_executable(test_gp ./test/test_gp.cpp)
target_include_directories(test_gp PUBLIC
${LIBGP_INCLUDE_DIR}
)
target_link_libraries(test_gp
gp
)
@baiwfg2
Copy link

baiwfg2 commented Oct 22, 2018

没说太清楚

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment