5

我正在从事的项目具有以下结构:

---Library1
------build
------include
------src
------CMakeLists.txt
---Library2
------build
------include
------src
------CMakeLists.txt
---Executable1
------build
------include
------src
------CMakeLists.txt

Library1是我正在开发的一个库,需要链接到Library2它是一个 3rd 方库。当我 build 时Library1,我需要它自动构建Library2并与之链接。Executable1将需要建立和链接Library1。我不确定如何使用 Cmake,我想知道是否有人可以引导我朝着正确的方向前进。我想我可能需要使用该add_dependencies命令,或者add_subdirectory但我不确定如何使用它们并确保它们链接到我的库。任何帮助,将不胜感激。

4

1 回答 1

6

I'd think the best commands here are likely to be add_subdirectory (as you suspected) and target_link_libraries.

I guess with your directory structure, I'd expect to see a "top-level" CMakeLists.txt in the root. In that CMake file, you'd invoke the subdirectories' CMakeLists using add_subdirectory.

I imagine both Library1 and Library2 are actual CMake targets, included via add_library, and similarly you have add_executable(Executable1 ...). In this case, you can add the following to Library1/CMakeLists.txt:

target_link_libraries(Library1 Library2)

CMake now automatically links Library2 whenever Library1 is specified as a dependency. If Library2 is modified, then it will be rebuilt automatically before being linked to Library1 again.

Likewise in Executable1/CMakeLists.txt you can then do:

target_link_libraries(Executable1 Library1)

Probably the only thing to watch for here is that the order of the add_subdirectory commands would need to be

add_subdirectory(Library2)
add_subdirectory(Library1)
add_subdirectory(Executable1)

so that the dependencies are defined before they're referred to in the target_link_libraries calls.

A final point which seems odd to me is that you have a build directory per target. Normally there should only be a need for a single build directory (preferably outside the source tree).

于 2013-05-24T00:28:33.177 回答