【问题标题】:CMake: add dependency to IMPORTED libraryCMake:将依赖项添加到 IMPORTED 库
【发布时间】:2016-08-23 16:30:46
【问题描述】:

我有一个供应商提供的库存档,已导入到我的项目中:

add_library(
    lib_foo 
    STATIC 
    IMPORTED GLOBAL
    )

set_target_properties(
    lib_foo 
    PROPERTIES IMPORTED_LOCATION             
    "${CMAKE_CURRENT_LIST_DIR}/vendor/foo.a"
    )

set_target_properties(
    lib_foo 
    PROPERTIES INTERFACE_INCLUDE_DIRECTORIES 
    "${CMAKE_CURRENT_LIST_DIR}/vendor"
    )

当我尝试使用此库链接应用程序时,我收到 undefined reference to 'pthread_atfork' 链接器错误:

/usr/lib/libtcmalloc_minimal.a(libtcmalloc_minimal_internal_la-static_vars.o):
    In function `SetupAtForkLocksHandler':
    /tmp/gperftools-2.4/src/static_vars.cc:119: 
        undefined reference to `pthread_atfork'
        ../vendor/foo.a(platformLib.o): In function `foo::Thread::Impl::join()':

所以vendor/foo.a 依赖于pthread

我试过target_link_libraries(lib_foo pthread) 但这不起作用,因为lib_fooIMPORTED 目标,而不是构建目标

CMake Error at libfoo/CMakeLists.txt:41 (target_link_libraries):
  Attempt to add link library "pthread" to target "lib_foo"
  which is not built in this directory.

问题:

如何将pthread 链接到lib_foo,或者指定依赖于lib_foo 的目标也依赖于pthread?

【问题讨论】:

    标签: c++ cmake


    【解决方案1】:

    IMPORTED_LINK_INTERFACE_LIBRARIES:

    您可以设置一个额外的目标属性,IMPORTED_LINK_INTERFACE_LIBRARIES

    IMPORTED 目标的传递链接接口。

    将此设置为包含其接口的库列表,当 IMPORTED 库目标链接到另一个目标。

    这些库将包含在目标的链接行中。

    LINK_INTERFACE_LIBRARIES 属性不同,此属性适用于所有导入的目标类型,包括STATIC 库。

    set_target_properties(lib_foo 
        PROPERTIES IMPORTED_LINK_INTERFACE_LIBRARIES 
        pthread
        )
    

    -pthread 编译器标志:

    但是,在这种特殊情况中,pthread 链接问题可能会通过将-pthread 添加到编译器标志来解决

    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread" )
    

    来自man gcc

    -pthread 通过 pthreads 库添加对多线程的支持。此选项为预处理器和链接器设置标志。

    它使文件用-D_REENTRANT 编译,并用-lpthread 链接。在其他平台上,这可能会有所不同。使用-pthread 以获得最大的可移植性。

    See this question for more information

    【讨论】:

    • 在 CMake 3.14 This property is deprecated. Use INTERFACE_LINK_LIBRARIES instead..
    猜你喜欢
    • 2019-06-24
    • 2023-04-07
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多