1 # This function is a helper that will merge static libraries.
4 # merge_static_libraries(mylib staticlibX staticlibY)
6 # mylib.a will generate a new static library mylib that is
7 # a combination of staticlibX and staticlibY
9 function(merge_static_libraries target)
11 set(dummy_source ${CMAKE_CURRENT_BINARY_DIR}/${target}_dummy.c)
12 add_library(${target} STATIC ${dummy_source})
16 list(REMOVE_DUPLICATES libs)
18 # validate that all libs are static
20 if (NOT TARGET ${lib})
21 message(FATAL_ERROR "${lib} not a valid target")
24 get_target_property(libtype ${lib} TYPE)
25 if(NOT libtype STREQUAL "STATIC_LIBRARY")
26 message(FATAL_ERROR "${lib} not a static library")
29 # add a dependency on the lib
30 add_dependencies(${target} ${lib})
33 # Force the merged Make the generated dummy source file depended on all static input
34 # libs. If input lib changes,the source file is touched
35 # which causes the desired effect (relink).
37 OUTPUT ${dummy_source}
38 COMMAND ${CMAKE_COMMAND} -E touch ${dummy_source}
41 # only LINUX is currently supported. OSX's libtool and windows lib.exe
42 # have native support for merging static libraries, and support for them
43 # can be easily added if required.
45 # generate a script to merge the static libraries in to the target
46 # library. see https://sourceware.org/binutils/docs/binutils/ar-scripts.html
47 set(mri_script "open $<TARGET_FILE:${target}>=")
49 # we use the generator expression TARGET_FILE to get the location
50 # of the library. this will not be expanded until the script file
52 set(mri_script "${mri_script} addlib $<TARGET_FILE:${lib}>=")
54 set(mri_script "${mri_script} save=end")
57 TARGET ${target} POST_BUILD
58 COMMAND echo ${mri_script} | tr = \\\\n | ${CMAKE_AR} -M)
61 message("-- MergeStaticLibraries: ${target}: merged ${libs}")
63 # we want to set the target_link_libraries correctly for the new merged
64 # static library. First we get the list of link libraries for each
65 # of the libs we are merging
68 get_property(trans TARGET ${lib} PROPERTY LINK_LIBRARIES)
69 list(APPEND link_libs ${trans})
73 # now remove the duplicates and any of the libraries we already merged
74 list(REMOVE_DUPLICATES link_libs)
76 list(REMOVE_ITEM link_libs ${lib})
79 # set the target link libraries
80 target_link_libraries(${target} ${link_libs})
82 message("-- MergeStaticLibraries: ${target}: remaining ${link_libs}")