4

我是使用 make 的新手,并且一直在通过本教程学习基础知识。这是教程中的最后一个示例 makefile 示例:

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)/*~ 

假设所有 .c 文件仅包含 hellomake.h,这应该可以正常工作,但如果每个 .c 文件包含不同的标头,则它不会工作。是否可以编写一个知道每个 .c 文件包含什么的makefile,所以我不必像这样手动进入:

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

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

因为这似乎会浪费很多时间。

4

3 回答 3

14

假设foo.c有一行:

#include "something.h"

你想在 makefile 中有一行:

foo.o: foo.c something.h

gcc 编译器可以为您构造该行。命令

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

将构建foo.ofoo.d包含该行。(尝试一下。)

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.)

于 2013-03-31T02:54:13.030 回答
0

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.

于 2013-04-07T10:56:09.913 回答
0

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

于 2017-09-29T13:08:46.797 回答