Automatically discovering C dependencies

前端 未结 5 1521
野的像风
野的像风 2020-12-14 12:17

I\'m required to write documentation for my current project that lists all .c files and for each one lists every .h file which is directly or indirectly included by that fil

5条回答
  •  半阙折子戏
    2020-12-14 12:46

    What I do in my Makefile is

    SRCS=$(wildcard *.c)
    
    depend: $(SRCS)
        gcc -M $(CFLAGS) $(SRCS) >depend
    
    include depend
    

    This means that if any of the source files are updated, the depend rule will run, and use gcc -M to update the file called depend. This is then included in the makefile to provide the dependency rules for all the source files.

    Make will check that a file is up to date before including it, so this depend rule will run if necessary whenever you run make without you needing to do a "make depend".

    This will run any time any file has changed. I've never found this a problem, but if you had a huge number of files in the directory you might find it took too long, in which case you could try having one dependency file per source file, like this:

    SRCS=$(wildcard *.c)
    DEPS=$(SRCS:.c=.dep)
    
    %.dep : %.c
        gcc -M $(CFLAGS) $< >$@
    
    include $(DEPS)
    

    Note that you can use -MM instead of -M to not include system headers.

提交回复
热议问题