Skip to content

Instantly share code, notes, and snippets.

@nyteshade
Last active February 4, 2025 17:49
Show Gist options
  • Save nyteshade/cbe0c03fee1c3991f1ba4a082149727e to your computer and use it in GitHub Desktop.
Save nyteshade/cbe0c03fee1c3991f1ba4a082149727e to your computer and use it in GitHub Desktop.
Fat / Universal Compilation for macOS x86_64 + ARM64
function fat() {
local output="${1}"
local files=($(printf "%s\n" "${2}"))
local GCC_ARGS=(${3:-$(printf "%s\n" "-std=c99 -Wall")})
if [ ${#} -eq 0 ]; then
local argfiles='"<\x1b[93mfile1\x1b[39m> <\x1b[93mfileN\x1b[39m>"'
local argopts='"<\x1b[93mgcc-opt1\x1b[39m> <\x1b[93mgcc-optN\x1b[39m>"'
local argout="<\x1b[93moutput-file\x1b[39m>"
printf "Usage: \x1b[36mfat\x1b[39m ${argout} ${argfiles} ${argopts}\n"
printf "where\n"
printf " \x1b[1moutput-file\x1b[22m the name of the output binary\n"
printf " \x1b[1mfile1-N\x1b[22m space separated quoted list of files\n"
printf " \x1b[1mgcc-opt-1-N\x1b[22m space separated quoted GCC arg list\n"
printf "\n"
printf "GCC options default to \"\x1b[1m-std=c99 -Wall\x1b[22m\"\n"
return 0
fi
for f in ${files[@]}; do
if [ ! -f "${f}" ]; then
printf "File ${f} not present on disk\n"
return 1
fi
done
gcc ${GCC_ARGS[@]} -arch x86_64 -o "${output}-x86_64" ${files[@]} && \
gcc ${GCC_ARGS[@]} -arch arm64 -o "${output}-arm64" ${files[@]} && \
lipo -create -output "${output}" "${output}-x86_64" "${output}-arm64" && \
rm "${output}-arm64" "${output}-x86_64"
if [ -f "${output}" ]; then
printf "\n\x1b[32mSuccessfully\x1b[39m compiled \x1b[1m${output}\x1b[22m.\n"
file "${output}"
return 0
else
printf "\nAn \x1b[31merror\x1b[39m occurred!\n"
return 1
fi
}
@nyteshade
Copy link
Author

A function that given the files tool.c and tool_helper.c could be universally/fat compiled using

fat tool "tool.c tool_helper.c"

By default, -std=c99 and -Wall are the default options but c11 for example could be used by supplying it as the only option at the end, such as

fat tool "tool.c tool_helper.c" -std=c11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment