CMake:如何检查是否使用 -stdlib=libc++ 编译了 STATIC 库?

时间:2021-06-07 10:48:45

标签: c++ cmake clang

我想检查我的所有依赖项是否都是使用 libc++ 编译的。如果不是这种情况,则返回警告或错误。我的一些依赖项是共享库,一些是静态的。对于共享库,我目前喜欢这个

if(MYLIB_FOUND)
    set (MYLIB_LIB "${MYLIB_LIBDIR}/lib${MYLIB_LIBRARIES}.so")
    set(MYLIB_FOUND TRUE)

    # Check if library has been compiled with -stdlib=libc++
    if(${CMAKE_VERSION} VERSION_LESS "3.16.0") 
        include(GetPrerequisites)
        GET_PREREQUISITES(${MYLIB_LIB} PREREQUISITES FALSE FALSE "" "")
        if (PREREQUISITES MATCHES "/libc\\+\\+")
            if(NOT USE_LIBCXX)
                message(WARNING "MyLib compiled using libc++ but this project does not use this flag")
                set(MYLIB_FOUND FALSE)
            endif()
        else()
            if(USE_LIBCXX)
                message(WARNING "MyLib not compiled using libc++ but this project requires this flag")
                set(MYLIB_FOUND FALSE)
            endif()
        endif()
    else()
        file(GET_RUNTIME_DEPENDENCIES RESOLVED_DEPENDENCIES_VAR MYLIB_DEPENDENCIES LIBRARIES ${MYLIB_LIB})
        if (MYLIB_DEPENDENCIES MATCHES "/libc\\+\\+")
            if(NOT USE_LIBCXX)
                message(WARNING "MyLib compiled using libc++ but this project does not use this flag")
                set(JMYLIB_FOUND FALSE)
            endif()
        else()
            if(USE_LIBCXX)
                message(WARNING "MyLib not compiled using libc++ but this project requires this flag")
                set(MYLIB_FOUND FALSE)
            endif()
        endif()
    endif()
else()
    set(MYLIB_FOUND FALSE)
endif()

我怎样才能对静态库做同样的事情? (主要是 CMake 3.8 及更高版本)

1 个答案:

答案 0 :(得分:0)

对于静态库,无需检查此项。静态库只是带有目标文件的档案,它们没有运行时依赖性。它们直接链接到您的最终二进制文件。

您应该阅读有关链接器工作原理的更多信息:

如果你在没有 libc++ 的情况下编译你的最终二进制文件并且没有任何“未定义的引用”错误 - 一切都很好。否则,如果未定义的符号是来自 lib++ 的函数,则您的静态库是使用 libc++ 支持编译的。

在链接阶段之前检查符号的唯一方法是检查静态库包含的符号。见this answer about how to do this