CMake - dependencies (headers) between apps/libraries in same project

后端 未结 2 1353
轻奢々
轻奢々 2020-12-25 14:57

I have the following project structure:

  • CMakeLists.txt
    • lib1/CMakeLists.txt and all cpp and header files of the lib
    • lib2/CMakeLists.txt and al
2条回答
  •  旧时难觅i
    2020-12-25 15:49

    Here's one possible solution:

    Root CMakeLists.txt:

    cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
    project(${PROJECT_NAME})
    add_subdirectory(lib1)
    add_subdirectory(lib2)
    add_subdirectory(app)
    


    lib1/CMakeLists.txt:

    project(Lib1)
    add_library(lib1 lib1.cpp lib1.h)
    


    lib2/CMakeLists.txt:

    project(Lib2)
    add_library(lib2 lib2.cpp lib2.h)
    
    # Add /lib1 to #include search path
    include_directories(${Lib1_SOURCE_DIR})
    # Specify lib2's dependency on lib1
    target_link_libraries(lib2 lib1)
    


    app/CMakeLists.txt:

    project(App)
    add_executable(app main.cpp some_header.h)
    
    # Add /lib1 and /lib2 to #include search path
    include_directories(${Lib1_SOURCE_DIR} ${Lib2_SOURCE_DIR})
    # Specify app's dependency on lib2.
    # lib2's dependency on lib1 is automatically added.
    target_link_libraries(app lib2)
    


    There are plenty of different ways to achieve the same end result here. For a relatively small project, I'd probably just use a single CMakeLists.txt:

    cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
    project(Test)
    
    add_library(lib1 lib1/lib1.cpp lib1/lib1.h)
    add_library(lib2 lib2/lib2.cpp lib2/lib2.h)
    add_executable(app app/main.cpp app/some_header.h)
    
    include_directories(${CMAKE_SOURCE_DIR}/lib1 ${CMAKE_SOURCE_DIR}/lib2)
    
    target_link_libraries(lib2 lib1)
    target_link_libraries(app lib2)
    


    For further info on the relevant commands and their rationale, run:

    cmake --help-command add_subdirectory
    cmake --help-command include_directories
    cmake --help-command target_link_libraries
    

提交回复
热议问题