2

I want to bundle five static libraries into one library in CMake. How can I proceed for this?

Like library a, b, c, d, and e should bundle into alpha_lib.

Kevin
  • 16,549
  • 8
  • 60
  • 74
jack sparow
  • 339
  • 3
  • 9
  • The question about combining static libraries into a single one is frequently asked. Have you tried to search such questions? E.g. how your question differs from that one: https://stackoverflow.com/questions/49945142/cmake-building-a-static-library-with-other-static-library. – Tsyvarev Feb 12 '20 at 14:39

1 Answers1

2

If you are using Visual Studio, you can take advantage of the Microsoft Library Manager (LIB.exe) to combine your static libraries into one. Your CMake could follow these steps:

  1. Use find_program() to have CMake locate the MSVC lib.exe tool on your system. If you run cmake from the Visual Studio Command Prompt, find_program can locate lib.exe automatically, without using the optional PATHS argument to tell it where to look.

  2. Use CMake's add_custom_target() command to call lib.exe using the syntax for merging libraries:

    lib.exe /OUT:alpha_lib.lib  a.lib b.lib c.lib d.lib e.lib
    

    You can use target-dependent generator expressions in the custom target command to have CMake resolve the locations of your built libraries. The custom target will create a Project in your Visual Studio solution that can be run separately to merge all of the built static libraries into one library.

Your CMake could look something like this:

# Create the static libraries (a, b, c, d, and e)
add_library(a STATIC ${a_SOURCES})
...
add_library(e STATIC ${e_SOURCES})

# Tell CMake to locate the lib.exe tool.
find_program(MSVC_LIB_TOOL lib.exe)

# If the tool was found, create the custom target.
if(MSVC_LIB_TOOL)
    add_custom_target(CombineStaticLibraries
        COMMAND ${MSVC_LIB_TOOL} /OUT:$<TARGET_FILE_DIR:a>/alpha_lib.lib
            $<TARGET_FILE:a> 
            $<TARGET_FILE:b> 
            $<TARGET_FILE:c> 
            $<TARGET_FILE:d> 
            $<TARGET_FILE:e> 
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    )
endif()
Kevin
  • 16,549
  • 8
  • 60
  • 74