Presuming MyLib.h
is a dependency for both of your C files, you should have something like this:
# Variables
CC := gcc
CFLAGS := -O
# Link executable
Tester: MyLib.o Tester.o
${CC} MyLib.o Tester.o ${LDFLAGS} -o Tester
# Compile object files
MyLib.o: MyLib.c MyLib.h
${CC} ${CFLAGS} -c -o MyLib.o MyLib.c
Tester.o: Tester.c MyLib.h
${CC} ${CFLAGS} -c -o Tester.o Tester.c
and, once you've got the hang of how things work, you can use the automatic variables as your second step in reducing code duplication:
# Variables
CC := gcc
CFLAGS := -O
# Link executable
Tester: MyLib.o Tester.o
${CC} $^ ${LDFLAGS} -o $@
# Compile object files
MyLib.o: MyLib.c MyLib.h
${CC} ${CFLAGS} -c -o $@ $<
Tester.o: Tester.c MyLib.h
${CC} ${CFLAGS} -c -o $@ $<
where $@
is the replaced by the name of the target for the current rule, $<
is replaced by the first (i.e. leftmost) dependency, and $^
is replaced by the full list of dependencies.
In the above, the bits after the :
are dependencies, i.e. the target to the left of the :
will be made/remade if any of the dependencies are more recent than the target. For each of the dependencies, make
will look for a target for it. So, for the first section, it sees that MyLib.o
and Tester.o
are dependencies for your overall executable, and it looks for targets for them, which are provided. Finding the targets, it builds them (if necessary) and then proceeds to build Tester
.
Note that CFLAGS
conventionally represents compilation flags, so you don't need to pass them when you're only linking since no compilation is being done at that point.
Also, if you're struggling with this kind of thing, then simplify, and remove all the additional targets (such as clean
and install
and all
) until you've got the hang of what's going on.