Makefile Header Dependencies

I am new to using make and have learned the basics through this tutorial . Here is an example makefile example from a 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 if all .c files contain only hellomake.h, but this will not work if each .c file contains different headers. Is it possible to write a makefile that knows what each .c file includes, so I don't have to go in and do it manually:

 foo.o: foo.c something.h ... bar.o: bar.c somethingelse.h ... 

because it looks like it will be a big waste of time.

+4
source share
3 answers

Suppose foo.c has a line:

 #include "something.h" 

You need a line in the makefile:

 foo.o: foo.c something.h 

The gcc compiler can build this line for you. Command

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

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

So just change your makefile to create these * .d files and include them, and everything will be ready:

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

(Further refinements are possible, such as indicating where * .d files should be).

+13
source

Traditional forms are quite limited and force you to do all these basic things yourself. If you rightly expect the build tool to find the dependencies and find out what to bind, try makepp . You may not need to make a file at all or just minimal

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

The linking part will require a little help on your side, as it is based on source-header pairs. If myprog.cpp includes ah and b.hpp , it will see if it can build ao and / or bo , and if so, it will link them together and recursively check that their sources include.

You will need to learn more make syntax if you have more complex requirements. But if so, then there is no limit. Besides doing just about everything GNU can do, there are many more useful things, and you can even extend your makefiles with some Perl programs.

0
source

Yes, the “MMD” flag will help you generate .d (dependency) files. If you include a Makefile (-include * .d) at the end of your file, and then if you make any changes to the .h file, the corresponding .o file will be restored.

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

0
source

All Articles