Pergunta

Most makefiles I have used in the past are very basic, using no more than a single command, such as how the clean command in the below code. Could someone please explain to me how this works? What exactly is OBJS and $@

# compiler to use
CC  = gcc

# object files needed for the project
OBJS    = main.o lex.yy.o error.o

# the main target
calc: $(OBJS)
    gcc -o $@ $(OBJS) -ll

# dependencies
main.o: main.c y.tab.h

error.o: error.h

lex.yy.o: lex.yy.c y.tab.h

lex.yy.c: simple-arith.l
        $(LEX) simple-arith.l

clean:
        $(RM) $(OBJS) lex.yy.c

Here is the ouput of the make command:

-bash-4.1$ make
gcc    -c -o main.o main.c
lex simple-arith.l
gcc    -c -o lex.yy.o lex.yy.c
gcc    -c -o error.o error.c
gcc -o calc main.o lex.yy.o error.o -ll
Foi útil?

Solução

OBJS is a variable. The object files are what your compiler outputs for each compilation unit, and will be fed into the linker.

calc: $(OBJS)
    gcc -o $@ $(OBJS) -ll

That line is telling Make to rebuild calc whenever any of the files in the $(OBJS) variable change. $@ is a special Make variable that refers to the name of the target (in this case calc).

What Make does is build a dependency graph of its targets. The targets come before the : and the dependencies come after. If any target needs to be built (like the default calc in the example) it will check all of its dependencies to see if any of them need to be rebuilt. Make uses the modification time to determine this; if a target is older than one of its dependencies, or the target doesn't exist, it needs rebuilding.

Outras dicas

OBJS is just a variable: OBJS = main.o lex.yy.o error.o

$@ is an Automatic Variable. http://www.gnu.org/software/make/manual/make.html#Automatic-Variables

$@ The file name of the target of the rule. If the target is an archive member, then ‘$@’ is the name of the archive file. In a pattern rule that has multiple targets (see Introduction to Pattern Rules), ‘$@’ is the name of whichever target caused the rule's recipe to be run.

So in this case:

calc: $(OBJS)
    gcc -o $@ $(OBJS) -ll

$@ is "calc"

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top