How to manage C header file dependencies?

て烟熏妆下的殇ゞ 提交于 2019-12-17 16:54:18

问题


I've a lot of C files, some have a header (.h), some files not.

Here's my makefile :

.SUFFIXES: 

SRC := $(wildard ./src/*.c)
OBJ := $(SRC:%.c=%.o)

all: $(OBJ)

%.o: %.c
    $(MyNotGCCCompiler) "@../$(*F).cmd"

It works fine except that if I change a header file, the target isn't recompiled because not included in the dependencies.

How can I manage this case?

Thanks


回答1:


The standard approach is to generate header dependencies automatically while compiling.

For the first compilation no dependencies are necessary since every source file must be compiled. Subsequent recompilations load dependencies generated by the previous compilation to determine what needs to be recompiled.

Your $(MyNotGCCCompiler) is likely to have a command line option to generate a dependencies file.

When using gcc it works like this:

.SUFFIXES: 

SRC := $(wildard ./src/*.c)
OBJ := $(SRC:%.c=%.o)
DEP := $(OBJ:%.o=%.d)

all: $(OBJ)

# when compiling produce a .d file as well 
%.o: %.c
    gcc -c -o $@ $(CPPFLAGS) $(CFLAGS) -MD -MP -MF ${@:.o=.d} $<

# don't fail on missing .d files
# there won't be any on the first run
-include $(DEP) 



回答2:


(I'm not sure how this is not stating the obvious, but anyway:)

Add rules to list those dependencies explicitly, file by file. Preferably in a separate makefile that you include from the main one.

Tools exist (such as gcc) that can generate them for you; if you can't use or build such a tool, you'll need to maintain these rules yourself.



来源:https://stackoverflow.com/questions/9598595/how-to-manage-c-header-file-dependencies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!