CMake: include library dependencies in a static library

后端 未结 2 919
心在旅途
心在旅途 2020-11-29 02:37

I am building a static library in CMake, which is dependent on many other static libraries. I would like them all to be included in the output .lib/.a file,

2条回答
  •  庸人自扰
    2020-11-29 02:46

    Okay, so I have a solution. First it's important to recognize that static libraries do not link other static libraries into the code. A combined library must be created, which on Linux can be done with ar. See Linking static libraries to other static libraries for more info there.

    Consider two source files:

    test1.c:

     int hi()
     {
       return 0;
     }
    

    test2.c:

    int bye()
    {
      return 1;
    }
    

    The CMakeLists.txt file is to create two libraries and then create a combined library looks like:

    project(test)
    
        add_library(lib1 STATIC test1.c)
        add_library(lib2 STATIC test2.c)
    
        add_custom_target(combined ALL
          COMMAND ${CMAKE_AR} rc libcombined.a $ $)
    

    The options to the ar command are platform-dependent in this case, although the CMAKE_AR variable is platform-independent. I will poke around to see if there is a more general way to do this, but this approach will work on systems that use ar.


    Based on How do I set the options for CMAKE_AR?, it looks like the better way to do this would be:

    add_custom_target(combined ALL
       COMMAND ${CMAKE_CXX_ARCHIVE_CREATE} libcombined.a $ $)
    

    This should be platform-independent, because this is the command structure used to create archives internally by CMake. Provided of course the only options you want to pass to your archive command are rc as these are hardwired into CMake for the ar command.

提交回复
热议问题