CMake and Static Linking

后端 未结 2 669
庸人自扰
庸人自扰 2020-12-04 14:35

I\'m using CMake in a project, and I\'m trying to statically link some libraries. I\'ve set:

set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS \"-static-         


        
相关标签:
2条回答
  • 2020-12-04 15:13

    I've managed to solve my problem by using the following:

    #Dynamic/Shared Libs
    ...
    #Static start
    set_target_properties(icarus PROPERTIES LINK_SEARCH_START_STATIC 1)
    set_target_properties(icarus PROPERTIES LINK_SEARCH_END_STATIC 1)
    set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
    #Static Libs
    ...
    #Set Linker flags
    set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")
    

    This works without passing a -static which creates other big issues, and can essentially mix static and dynamic libraries.

    As long as the order of static libraries is correct, and as long as dependencies of static libraries are satisfied, I get an ELF using some dynamic libraries (i.e. in my case mysqlclient, libmysql++) and the rest are all static libraries (crypto++, PocoNet, PocoUtil, PocoXML, PocoFoundation).

    Bear in mind that static linked libraries have their own dependencies. Examining my debug application using readelf -d app, I see:

    Dynamic section at offset 0x508f88 contains 28 entries:
      Tag        Type                         Name/Value
     0x0000000000000001 (NEEDED)             Shared library: [libmysqlpp.so.3]
     0x0000000000000001 (NEEDED)             Shared library: [libmysqlclient.so.18]
     0x0000000000000001 (NEEDED)             Shared library: [libm.so.6]
     0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
     0x0000000000000001 (NEEDED)             Shared library: [ld-linux-x86-64.so.2]
     0x0000000000000001 (NEEDED)             Shared library: [libpthread.so.0]
    

    I know that pthread is imported by Poco::Runnable, libm is for math operations, etc. I am still unaware if this is the right way to use CMake for partial static linking.

    In the case of Debian packaged libraries, such as crypto++, mysql++, mysqlclient, simply finding the *.a library worked, but in case of Poco Libraries, which only got me the full path and name of the library, but not a flag, -Bdynamic could only be turned off by using the above lines.

    Note: Poco could not be linked statically, without -static-libstdc++

    I hope this helps anyone stuck at something similar.

    0 讨论(0)
  • 2020-12-04 15:26

    How do I setup for static linkage using CMake

    Well... you don't :) That's not how CMake works: in CMake, you first find the absolute path of a library, then link to it with target_link_libraries.

    So, if you want to link to a static library, you need to search for that static library:

    find_library(SOMELIB libsomelib.a)
    

    instead of:

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