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

后端 未结 2 1375
轻奢々
轻奢々 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条回答
  •  清酒与你
    2020-12-25 15:45

    Project
     CMakeLists.txt
     \-lib1
       CMakeLists.txt
       \- include \ lib1
       \- src
     \-lib2
       CMakeLists.txt
       \- include \ lib2
       \- src
     \-app
       CMakeLists.txt
       \- src
    

    Suppose dependencies as follow:

    lib1 ---> lib2 ---> app 
       \--------------> app
    

    Something like this:

    CMakeLists.txt:

    add_subdirectory(lib1)
    add_subdirectory(lib2)
    add_subdirectory(app)
    

    lib1/CMakeLists.txt:

      file(GLOB_RECURSE _HDRS "include/*.hpp")
      file(GLOB_RECURSE _SRCS "src/*.[hc]pp")
      add_library(lib1 ${_HDRS} ${_SRCS})
      #target_link_libraries(lib1)
      target_include_directories(lib1 PUBLIC include)
    
      install(TARGETS lib1 DESTINATION lib)
      install(FILES ${_HDRS} DESTINATION include/lib1)
    

    lib2/CMakeLists.txt:

      file(GLOB_RECURSE _HDRS "include/*.hpp")
      file(GLOB_RECURSE _SRCS "src/*.[hc]pp")
      add_library(lib2 ${_HDRS} ${_SRCS})
      target_link_libraries(lib2 lib1)
      target_include_directories(lib2 PUBLIC include)
    
      install(TARGETS lib2 DESTINATION lib)
      install(FILES ${_HDRS} DESTINATION include/lib2)
    

    so in lib2/src/file.cpp you could do #include

    app/CMakeLists.txt:

      file(GLOB_RECURSE _SRCS "src/*.[hc]pp")
      add_executable(app ${_SRCS})
      target_link_libraries(app lib1 lib2)
    
      install(TARGETS app DESTINATION bin)
    

    so in app/src/file.cpp you could do #include and #include

    The magic is target_include_directories which attach the "include" directory to the target, so when linking with it you pull the include directory also ;)

提交回复
热议问题