How to ensure a target is run before all the other build rules in a makefile?

后端 未结 2 682
南旧
南旧 2020-11-28 13:23

I have a C++ project which contains a generated file that all the other C++ files depend on. I\'m trying to force that file to be generated and compiled before any other com

相关标签:
2条回答
  • 2020-11-28 13:54

    If you're sure that's really what you want, here's one way to do it: have a rule for a dummy file which the makefile will include.

    .PHONY: dummy
    dummy:
        # generate the file here
    
    -include dummy
    

    No matter what target you specify, Make will first run the dummy rule, then restart itself.

    0 讨论(0)
  • 2020-11-28 13:54

    Actually, other cpp files don't depend on the generated one (in terms of Make rules). Dependency graph still looks like:

    program
     |
     ^- file1.o
     |   ^- file1.c
     |
     ^- file2.o
     |   ^- file2.c
     |
     ^- generated_file.o
         ^- generated_file.c
             ^- <generator prerequisites>
    

    Your source files could only depend on some kind of generated header file (in case when it is #included by these sources).

    If you need to generate only a cpp file then the following makefile should be sufficient:

    srcs := $(wildcard src/*.cpp src/*/*.cpp)
    
    gen_file := gen/generated_file.cpp
    srcs += $(gen_file)
    
    objs := $(srcs:.cpp=.o)
    
    .PHONY : all
    all : program
    
    program : $(objs)
        @$(LD) ...
    
    %.o : %.c
        @$(CC) ...
    
    $(gen_file) :
        # generate the file here
    

    UPD.

    A little improvement based on Beta's answer.

    -include generator-task
    .PHONY : generator-task
    
    generator-task : $(gen_files)
    
    $(gen_files) : $(gen_prerequisites)
        # generate the file here
    

    Instead of running generator on each invocation of Make, this will only regenerate a file when one of its prerequisites would change.

    0 讨论(0)
提交回复
热议问题