-1

I have 3 files: MyLib.h MyLib.c Tester.c I've been trying to create the makefile but it is proving difficult.

I can do it when it is only one file, like below where I am compiling Hello.c

I have seen some examples but they seem a lot more complicated than the one I am using below -- which sort of makes sense to me.

BINDIR =    /usr/local/sbin
CC =        gcc
CFLAGS =    -O

all:        Hello

Hello:  Hello.o
    ${CC} ${CFLAGS} Hello.o ${LDFLAGS} -o Hello


Hello.o:    Hello.c
    ${CC} ${CFLAGS} -c Hello.c


install:    all
    rm -f ${BINDIR}/Hello
    cp Hello ${BINDIR}/Hello



clean:
    rm -f Hello  *.o core core.* *.core

Please help.

I been typing this every time I turn on my computer, kind of annoying by now.

gcc MyLib.c Tester.c -o Tester
Mike John
  • 818
  • 4
  • 11
  • 29

2 Answers2

0

Crude but effective:

Tester:
    gcc MyLib.c Tester.c -o Tester

Better:

CC = gcc

Tester: MyLib.o Tester.o
    $(CC) $^ -o $@

And I'll just make a guess about dependency:

MyLib.o Tester.o : MyLib.h

More sophisticated makefiles are possible, but this should do for now.

Beta
  • 96,650
  • 16
  • 149
  • 150
0

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.

Crowman
  • 25,242
  • 5
  • 48
  • 56