GCC dependency generation for a different output directory

后端 未结 7 433
深忆病人
深忆病人 2021-01-30 14:30

I\'m using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency f

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 15:06

    I'm assuming you're using GNU Make and GCC. First add a variable to hold your list of dependency files. Assuming you already have one that lists all our sources:

    SRCS = \
            main.c \
            foo.c \
            stuff/bar.c
    
    DEPS = $(SRCS:.c=.d)
    

    Then include the generated dependencies in the makefile:

    include $(DEPS)
    

    Then add this pattern rule:

    # automatically generate dependency rules
    
    %.d : %.c
            $(CC) $(CCFLAGS) -MF"$@" -MG -MM -MP -MT"$@" -MT"$(<:.c=.o)" "$<"
    
    # -MF  write the generated dependency rule to a file
    # -MG  assume missing headers will be generated and don't stop with an error
    # -MM  generate dependency rule for prerequisite, skipping system headers
    # -MP  add phony target for each header to prevent errors when header is missing
    # -MT  add a target to the generated dependency
    

    "$@" is the target (the thing on the left side of the : ), "$<" is the prerequisite (the thing on the right side of the : ). The expression "$(<:.c=.o)" replaces the .c extension with .o.

    The trick here is to generate the rule with two targets by adding -MT twice; this makes both the .o file and the .d file depend on the source file and its headers; that way the dependency file gets automatically regenerated whenever any of the corresponding .c or .h files are changed.

    The -MG and -MP options keep make from freaking out if a header file is missing.

提交回复
热议问题