Makefile header dependencies

2019-01-12 07:25发布

I am new to using make and have been learning the basics through this tutorial. Here is the final example makefile example from the tutorial:

IDIR =../include
CC=gcc
CFLAGS=-I$(IDIR)

ODIR=obj
LDIR =../lib

LIBS=-lm

_DEPS = hellomake.h
DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS))

_OBJ = hellomake.o hellofunc.o 
OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ))


$(ODIR)/%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

hellomake: $(OBJ)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

.PHONY: clean

clean:
    rm -f $(ODIR)/*.o *~ core $(INCDIR)/*~ 

This should work fine assuming all .c files are only including hellomake.h, but it wouldn't work if each .c file was including different headers. Is it possible to write a makefile that knows what each .c file is including, so I don't have to go in and do it manually like:

foo.o: foo.c something.h
    ...

bar.o: bar.c somethingelse.h
    ...

because that seems like it would be a big waste of time.

标签: makefile
3条回答
放我归山
2楼-- · 2019-01-12 07:42

Yes, the "MMD" flag will help you to generate ".d" file (dependency) files. If you include at end of your Makefile( -include *.d ) and then if you make any change in .h file, the respective .o file, will rebuild.

Take this as reference: https://github.com/saanvijay/makefile-skeleton

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-12 07:45

Traditional makes are rather limited and force you to do all that basic stuff yourself. If you rightly expect a build tool to find dependencies and know what to link, try makepp. You may not need a makefile at all, or just a minimal one like

CFLAGS = -O3
myprog:                # just a default target to know what to build

The linking part would require a little help on your side, in that it is based on source-header pairs. If myprog.cpp includes a.h and b.hpp it'll look if it can build a.o and/or b.o, and if so, will link them and recursively check what their sources include.

You will only need to learn more make syntax, if you have more complex requirements. But if you do, there is no limit. Besides doing almost all that GNU make can, there are lots more useful things, and you can even extend your makefiles with some Perl programming.

查看更多
唯我独甜
4楼-- · 2019-01-12 07:49

Suppose foo.c has a line:

#include "something.h"

You'd like a line in the makefile:

foo.o: foo.c something.h

The gcc compiler can construct that line for you. The command

gcc -MMD -c -o foo.o foo.c

will build foo.o and foo.d which contains the line. (Try it.)

So just modify your makefile to produce these *.d files and include them, and you're done:

$(ODIR)/%.o: %.c $(DEPS)
    $(CC) -MMD -c -o $@ $< $(CFLAGS)

-include $(ODIR)/*.d

(Further refinements are possible, like specifying where the *.d files should go.)

查看更多
登录 后发表回答