Makefile标头依赖项 [英] Makefile header dependencies

查看:52
本文介绍了Makefile标头依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是不熟悉make的新手,并且已经通过此基础学习了基础知识教程.这是教程中的最后一个示例makefile示例:

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

假设所有.c文件都仅包含hellomake.h,则此方法应该可以正常工作,但是如果每个.c文件都包含不同的头文件,则此方法将无效.是否有可能编写一个知道每个.c文件包括哪些内容的makefile,所以我不必手动进行操作,例如:

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.

推荐答案

假设foo.c有一行:

#include "something.h"

您想要在makefile中添加一行:

You'd like a line in the makefile:

foo.o: foo.c something.h

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

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

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

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

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

因此只需修改您的makefile来生成这些* .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

(可以进一步细化,例如指定* .d文件应放在的位置.)

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

这篇关于Makefile标头依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆