Why use add_library({tgt} IMPORTED) versus target_link_libraries( -l {.so | .a})?

后端 未结 1 1795
误落风尘
误落风尘 2021-02-04 14:18

What is the purpose of using the statement:

add_library( [SHARED|STATIC] IMPORTED)

From what I have found even if you create an impo

相关标签:
1条回答
  • 2021-02-04 14:37

    You should use add_library(<tgt> [SHARED|STATIC] IMPORTED) whenever you need to set properties such as dependencies, compile definitions, compile flags etc for <tgt>, and/or by extension, any targets that are linking against <tgt>.

    Let's say you have two static libraries; libfoobar.a and libraboof.a, where libfoobar.a requires libraboof.a. Let's also say that these libraries contain some features that are enabled by -DSOME_FEATURE.

    add_library(raboof STATIC IMPORTED)
    set_target_properties(raboof PROPERTIES
        IMPORTED_LOCATION <path-to-libraboof.a>
        INTERFACE_COMPILE_DEFINITIONS "SOME_FEATURE"
    )
    
    add_library(foobar STATIC IMPORTED)
    set_target_properties(foobar PROPERTIES
        IMPORTED_LOCATION <path-to-libfoobar.a>
        INTERFACE_LINK_LIBRARIES raboof
    )
    

    So when you link against libfoobar.a:

    add_executable(my_app main.cpp)
    target_link_libraries(my_app foobar)
    

    CMake will make sure to link all dependencies in the correct order and will in this case also append -DSOME_FEATURE to the compile flags when you build my_app. Note that since we added libraboof.a as a dependency to libfoobar.a, -DSOME_FEATURE is added to any target that link against libfoobar.a through the transitive property.

    If you don't use add_library(<tgt> <SHARED|STATIC> IMPORTED) in a scenario like this, you would have to manage any dependencies and required build options yourself for each target, which is quite error-prone.

    This method is also often used in Config-modules for multi-component libraries to manage dependencies between the components.

    0 讨论(0)
提交回复
热议问题