GNU Make. Why this complex syntax to generate dependencies?

后端 未结 3 720
醉梦人生
醉梦人生 2020-12-09 23:07

I\'m reading Managing Projects with GNU Make, and found this example in Chapter 2.7 - Automatic Dependency Generation. The Author says their from the GNU manual:

<         


        
相关标签:
3条回答
  • 2020-12-09 23:09

    Actually even the rule itself is not necessary. There is a great overview of different approaches of generating Make-style dependencies in Advanced Auto-Dependency Generation article written by Paul D. Smith.

    After all, the following rule should be enough (in case of using GCC):

    %.o: %.c
        $(CC) $(CPPFLAGS) $(CFLAGS) -MMD -MP -o $@ -c $<
    
    -include $(SOURCES:.c=.d)
    

    UPD.

    I have also answered a similar question a bit earlier. It contains an explanation (quotation of GCC manual) of -MMD -MP options.

    0 讨论(0)
  • 2020-12-09 23:20

    Addressing the question: Why do a redirect of the file into sed? If you do:

    @$(CC) -M $(CPPFLAGS) $<  | sed 's|:| $*.d : |'  > $@;
    

    and the compilation fails (errors out and generates no output), you will create an empty target file. When make is run again, it will see the newly created empty file and not regenerate it, leading to build errors. Using intermediate files is a common defensive strategy to avoid accidentally created an empty target.

    0 讨论(0)
  • 2020-12-09 23:24

    An even simpler solution is to get rid of the sed call completely, as gcc can do everything you need directly:

    %.d: %.c
            $(CC) -M $(CPPFLAGS) -MF $@ $< -MT "$*.o $@"
    
    0 讨论(0)
提交回复
热议问题