CMake:为什么一个added_sub目录对其他子目录不可见

时间:2018-09-22 16:25:14

标签: c++ cmake

我具有以下项目结构:

project
  - CMakeLists.txt
  - src
  - LibA
    - CMakeLists.txt
  - LibB
    - CMakeLists.txt

根CMakeLists.txt看起来像这样:

add_subdirectory(LibA)
add_subdirectory(LibB)
add_executable(foo src/main.cpp)
target_link_libraries(foo LibA LibB)

但是,LibB实际上也希望使用LibA的某些功能。但是,我无法从LibB中访问LibA。但是我也不能将其添加为子目录。对我来说这是一个真正的问题。我该如何最好地解决它?

谢谢。

1 个答案:

答案 0 :(得分:0)

要说的解决方案有点复杂,但是我想以一种简化的方式来解释它...

项目结构应为:

 /src
   |
   +-- /lib-a
   |     +-- /includes
   |     +-- /sources
   |     +-- LibAConfig.cmake
   |     \-- CMakeLists.txt
   +-- /lib-b
   |     +-- /includes
   |     +-- /sources
   |     +-- LibBConfig.cmake
   |     \-- CMakeLists.txt
   \-- /main
   |     +-- /includes
   |     +-- /sources
   |     \-- CMakeLists.txt
   \-- CMakeLists.txt

/src/lib-a/LibAConfig.cmake 应该是:

# Debug

MESSAGE ("-- Library A configuration...")

# Headers

include_directories(${CMAKE_CURRENT_LIST_DIR}/includes)

/src/lib-a/CMakeLists.txt 应该是:

# Define project

project(LibA CXX)

# Debug

message("-- Working on \"${CMAKE_CURRENT_SOURCE_DIR}\"...")

# Package registration

set(LibA_DIR ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL "")

# Project files

include_directories(includes)
file(GLOB _SOURCES sources/*.cpp)

# Go on with your module setup...

/src/lib-b/LibBConfig.cmake 应该是:

# Debug

MESSAGE ("-- Library B configuration...")

# Headers

include_directories(${CMAKE_CURRENT_LIST_DIR}/includes)

/src/lib-b/CMakeLists.txt 应该是:

# Define project

project(LibB CXX)

# Debug

message("-- Working on \"${CMAKE_CURRENT_SOURCE_DIR}\"...")

# Package registration

set(LibB_DIR ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL "")

# Project files

include_directories(includes)
file(GLOB _SOURCES sources/*.cpp)

# Reference/Link to LIB-A

find_package(LibA)

# Go on with your module setup...

/src/main/CMakeLists.txt 应该是:

# Define project

project(MainApp CXX)

# Debug

message("-- Working on \"${CMAKE_CURRENT_SOURCE_DIR}\"...")

# Project files

include_directories(includes)
file(GLOB _SOURCES sources/*.cpp)

# Reference/Link to LIB-A and LIB-B

find_package(LibA)
find_package(LibB)

# Go on with your module setup...

/src/CMakeLists.txt 应该是:

# Define project

project(MyProject CXX)

# Debug

message("-- Working on \"${CMAKE_CURRENT_SOURCE_DIR}\"...")

add_subdirectory(lib-a)
add_subdirectory(lib-b)
add_subdirectory(main)

# Go on with your module setup...

我从我的一个项目中摘取了以上示例...