-#!/bin/bash
+#!/usr/bin/env bash
# predeclare our variables
declare -a objects
declare -a libpaths
declare -a libraries
compile=false
+runtime='
+#define _POSIX_C_SOURCE 200809L
+#define _XOPEN_SOURCE 700
+#define AUTOLIB(n) \
+ int __autolib_##n __attribute__ ((weak));'
# scan the rest of the options for lib paths, libs and objects
for i do
objects+=("$i") ;;
-L*) # Add libpaths to the search list
- libpaths+=("$i") ;;
+ libpaths+=("${i#-L}") ;;
-c) # Mark this as compilation only
compile=true ;;
esac
done
-# generate the autolib include file
-gendir="/tmp/$USER"
-genfile="autolib.h"
-genmacro="#define AUTOLIB(n) static int __autolib_##n = 1"
-if [[ ! -f "$gendir/$genfile" ]]; then
- mkdir -p "$gendir"
- printf '%s' "$genmacro" > "$gendir/$genfile"
-fi
-
-# execute the compiler
+# if we're compiling, generate the header, compile, and exit
if $compile; then
- cc -include "$gendir/$genfile" "$@"
-else
- echo cc "$@"
+ genfile=$(mktemp)
+ printf '%s\n' "$runtime" > "$genfile"
+ cc -include "$genfile" "$@"
+ status=$?
+ rm "$genfile"
+ exit "$status"
fi
+
+# scan objects/libs for referenced libraries
+scan_for_libs(){
+ nm "$@" | sed -n '/__autolib/ s/.*_\+autolib_// p' | sort -u
+}
+
+# if we made it here, we must be linking. scan for dependencies
+mapfile -t libraries < <(scan_for_libs "${objects[@]}")
+cc "$@" "${libraries[@]/#/-l}"