Skip to content

Instantly share code, notes, and snippets.

@mstorsjo
Forked from evands/combine_static_libraries.sh
Last active April 3, 2023 07:50
Show Gist options
  • Save mstorsjo/d462f8afcf1d3f5b25d590804682e97d to your computer and use it in GitHub Desktop.
Save mstorsjo/d462f8afcf1d3f5b25d590804682e97d to your computer and use it in GitHub Desktop.
Combine multiple .a static libraries, which may each have multiple architectures, into a single static library
#!/bin/sh
# Combined all static libaries in the current directory into a single static library
# It is hardcoded to use the i386, x86_64, armv7, armv7s and arm64 architectures; this can easily be changed via the 'archs' variable at the top
# The script takes a single argument, which is the name of the final, combined library to be created.
#
# For example:
# => combine_static_libraries.sh combined-library
#
# Script by Evan Schoenberg, Regular Rate and Rhythm Software
# Thanks to Claudiu Ursache for his blog post at http://www.cvursache.com/2013/10/06/Combining-Multi-Arch-Binaries/ which detailed the technique automated by this script
#####
# $1 = Name of output archive
#####
archs=(i386 x86_64 armv7 armv7s arm64)
libraries=(*.a)
libtool="/usr/bin/libtool"
echo "Combining ${libraries[*]}..."
for library in ${libraries[*]}
do
lipo -info $library
# Extract individual architectures for this library
for arch in ${archs[*]}
do
lipo -thin $arch $library -o ${library}_${arch}.a
done
done
# Combine results of the same architecture into a library for that architecture
source_combined=""
for arch in ${archs[*]}
do
source_libraries=""
mkdir $arch
cd $arch
for library in ${libraries[*]}
do
# Extract the libraries, overwriting duplicated files with the same name in each lib
ar x ../${library}_${arch}.a
rm __.SYMDEF
# Hack specific to one usecase: don't deduplicate Utils.o, both versions must be kept
mv Utils.o ${library}_Utils.o
source_libraries="${source_libraries} ${library}_${arch}.a"
done
cd ..
$libtool -static ${arch}/*.o -o "${1}_${arch}.a"
source_combined="${source_combined} ${1}_${arch}.a"
# Delete intermediate files
rm ${source_libraries}
rm -rf ${arch}
done
# Merge the combined library for each architecture into a single fat binary
lipo -create $source_combined -o $1.a
# Delete intermediate files
rm ${source_combined}
# Show info on the output library as confirmation
echo "Combination complete."
lipo -info $1.a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment