【问题标题】:CMake : multiple subprojects using the same static libraryCMake:使用同一个静态库的多个子项目
【发布时间】:2011-12-09 00:28:40
【问题描述】:

我正在使用 cmake 编译我的一个工作项目,这是交易

-
  client/
    CMakeLists.txt
  server/
    CMakeLists.txt
  libs/
    libstuff/
      CMakeLists.txt
  CMakeLists.txt

所以我希望能够单独编译每个子项目,并从根文件夹构建客户端和服务器。

假设客户端和服务器需要 libstuff。

我尝试在客户端和服务器 CMakeLists.txt 中使用带有 lib 路径的“add_subdirectory”,当您编译服务器或客户端时它可以工作,但如果您尝试从根目录运行:

CMake Error at common/libplugin/CMakeLists.txt:33 (ADD_LIBRARY):
  add_library cannot create target "plugin" because another target with the
  same name already exists.  The existing target is a static library created
  in source directory "/home/adrien/git/r-type/common/libplugin".  See
  documentation for policy CMP0002 for more details.

所以我是一个带 cmake 的新人,我不确定我应该做什么,我应该使用 add_dependencies 吗?

感谢您的帮助,

【问题讨论】:

  • “单独编译”是什么意思?如果构建VS项目或者makefile,可以选择编译哪个项目...

标签: static cmake


【解决方案1】:

一个简单的解决方案是使用 TARGET 条件来保护客户端和服务器 CMake 列表文件中的 add_subdirectory 调用,即:

if (NOT TARGET plugin)
    add_subdirectory("${CMAKE_SOURCE_DIR}/common/libplugin")
endif() 

这可以防止多次添加libplugin 子目录。

【讨论】:

【解决方案2】:

我建议将三个 add_subdirectory 调用放在根 CMakeLists.txt 中。首先是 libstuff,然后是客户端和服务器....

将 Stuff 项目设置为独立的,但将变量添加到 cmake 缓存中,以便其他项目可以“导入”它。然后,在客户端和服务器中,您可以参考 Stuff 项目...使用普通调用 include_directoriestarget_link_libraries

例如在 libstuff...

# libstuff CMakeLists
project( Stuff )
# ... whatever you need here: collect source files, ...
add_library( LibStuff ${Stuff_Sources} )
# Then, define a very useful variables which gets exported to the cmakecache and can be 
# used by other cmakelists
set( STUFF_INCLUDE_DIRS ${Stuff_SOURCE_DIR} CACHE STRING "Include-dir for Stuff." FORCE )

然后在客户端(同样在服务器中)

# client CMakeLists
project( Client )
# refer to Stuff-includes here...
include_directories( ${STUFF_INCLUDE_DIRS} )

add_executable( Client client.h client.cpp main.cpp ) # 
target_link_libraries( Client LibStuff )

然后您可以只“编译”客户端目录,方法是进入客户端目录并在那里运行 make 或 msbuild。或者,您可以在根 cmakelistt 中添加一个 cmake 标志,用于在客户端、服务器或两者之间进行过滤...

【讨论】:

  • 这个解决方案很好,可以连续编译服务器和客户端,但我无法编译独立客户端或独立服务器...
  • 确实如此,但您可以进入客户端(或服务器)目录并从那里编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2012-07-10
  • 2017-10-02
相关资源
最近更新 更多