#!/bin/sh
#
# CCDEPS-GCC (C) 2002 Emile van Bergen. Distribution of this file is allowed
# under the conditions detailed in the GNU General Public License (GPL). See 
# the file COPYING for more information.
#
# This script compiles and/or links one or more source or object files into a
# object file or executable target, and outputs all extra dependencies found
# while doing so in a file named target.d, which can be used by GNU Make.
#
# The script should be invoked the same way as your C compiler, that is,
# specifying the target using a -o option and the source or object files as 
# non-option arguments. It will generate dependencies in the form
#
# target target.d: dir/file1.c dir/file2.c header1.h header2.h
# dir/file1.c dir/file2.c header1.h header2.h:
#
# This version is intended for GCC, which can do compilation and dependency
# generation in one step. The name of the GCC version (default gcc) can be
# overridden using the CC environment variable.

cmdline="$*"

while [ x"$1" != x ]
do
	case "$1" in
		-o) tgt="$2" ; shift ;;	# target specifier option
		-x|-u|-b|-V) shift ;;	# options with arg after space
		-*) ;;			# standard options
		*) fil="$fil $1" ;;	# source or object files
	esac
	shift
done

if [ x"$CC" = x ]
then
	CC=gcc
	export CC
fi

# If we're not processing any .c files (link only), run gcc as-is and we're done

expr "$fil" : ".*\.c" >/dev/null || exec $CC $cmdline

# Otherwise, run the gcc with the -MD option, which generates a .d file
# in the current directory for each .c or .cc source file processed.
#
# These files are post-processed (replacing the incorrectly named target
# with the real target specified with -o, and adding the .d file), concatenated
# into one .d file that is named based on the target name, and put in the
# correct directory. Further, all prerequisites are added as bare targets,
# preventing errors when files are missing due to renaming or restructuring
# headers, but causing the files dependent on them to be considered out of
# date. (GNU Make feature).
#
# Makefiles must include the .d files like this: -include $(OBJS_$(d):.o=.d)
# or, when compiling and linking in one step: -include $(TGTS_$(d):%=%.d)

$CC -MD $cmdline

tmp=`echo $fil | sed -e 's/[^ 	]*\.[^c]//' -e 's/\.c/\.d/g' -e 's%.*/%%g'`
dep=$tgt.d

rm -f $dep
for tf in $tmp
do
	mv $tf $dep.tmp || exit 1
	sed -e "s%.*:%$tgt $dep:%" < $dep.tmp >> $dep
	sed -e 's%^.*:%%' -e 's%^ *%%' -e 's% *\\$%%' -e 's%$%:%' \
		< $dep.tmp >> $dep
	rm -f $dep.tmp
done



syntax highlighted by Code2HTML, v. 0.9.1