Resolving dependencies of orthogonal modules

Viewed 37

I have a project composed of several modules and I would like to use CMake's add_subdirectory function:

Project
+ CMakeLists.txt
+ bin
+  (stuff that depends on lib/)
+ lib
    module1
    + CMakeLists.txt
    + (cpp,hpp)
    module2
    + CMakeLists.txt
    + (cpp,hpp)
    module3
    + CMakeLists.txt
    + (cpp,hpp)
    logging.cpp
    logging.hpp

These top-level modules are independent from each other, but they all depend on the logging module. When I move the relevant top-level module code from the root CMakeLists into specific subdirectories, I am not able to compile them with make because the logging module is missing.

Is there a way to program the dependency on the logging module into CMakeLists of the top-level modules, or will it be resolved automatically when calling cmake in the root directory?

1 Answers

Is there a way to program the dependency on the logging module into CMakeLists of the top-level modules...

Yes, you can define a CMake library target for the logging functionality in the root CMakeLists.txt file.

CMakeLists.txt:

cmake_minimum_required(VERSION 3.16)

project(MyBigProject)

# Tell CMake to build a shared library for the 'logging' functionality.
add_library(LoggingLib SHARED
    lib/logging.cpp
)
target_include_directories(LoggingLib PUBLIC ${CMAKE_SOURCE_DIR}/lib)

# Call add_subdirectory after defining the LoggingLib target.
add_subdirectory(lib/module1)
add_subdirectory(lib/module2)
add_subdirectory(lib/module3)

...

Then, simply link the logging library target to your other module targets that need it. For example:

lib/module1/CMakeLists.txt:

project(MyModule1)

# Tell CMake to build a shared library for the 'Module1' functionality.
add_library(Module1Lib SHARED
    ...
)

# Link the LoggingLib target to your Module1 library target.
target_link_libraries(Module1Lib PRIVATE LoggingLib)

Note, this assumes you run CMake from the root of the project. If you run CMake directly on the lib/module1/CMakeLists.txt file, for example, it will not have access to the logging target defined in the root CMakeLists.txt file.

Related