12

If makefile changes, make rebuilds all targets right?

But how to tell make that if after makefile changed, it shall run make clean and then make?

Or how to instruct make to run some other command in that situation? Do I have to write a special kind of target?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
devemouse
  • 5,302
  • 5
  • 22
  • 22

3 Answers3

4

You could try this:

all: Makefile.uptodate yourMainTarget

Makefile.uptodate: Makefile
    make clean
    touch Makefile.uptodate

I'm not a make expert so I don't know if that's a horrible hack, but it worked in my limited tests ;-)

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 3
    This will break for parallel builds (with `-j`), as it may run `make clean` at the same time as it is building for `yourMainTarget`. – C0deH4cker Sep 28 '16 at 23:46
  • ^ "This will break for parallel builds" Correct. To fix, add a dependency to `yourMainTarget` like so: `yourMainTarget: Makefile.uptodate `. Then also add it in a similar fashion to all other targets, e.g. `.o` files for compiling C/C++ code or something. This will force it to resolve the commands under the `Makefile.uptodate` target before starting the build of `yourMainTarget` or any of its dependencies, which allows the clean to finish before e.g. compiling anything or running anything. – Keith M Mar 04 '19 at 15:48
4

Crude but effective (I can't think of anything more elegant):

include marker

marker: Makefile
    @touch $@
    $(MAKE) clean
    $(MAKE)
Beta
  • 96,650
  • 16
  • 149
  • 150
  • I don't think you need the `$(MAKE)` at the end; that should be handled by the initial entry of the Makefile. Right? Clever using `include` though! – Keith M Mar 22 '19 at 01:07
2

I believe that you want to run clean automatically because you want certain targets to be rebuilt whenever make is called. This can be achieved by adding a dependency named FORCE to the rule whose target you want to build always and then define FORCE like this: ie no rule and no dependency.

FORCE:

Please see http://www.gnu.org/software/make/manual/make.html#Force-Targets

If you want all files to be recompiled, you add the following to the makefile:

%.o : %.cpp FORCE
    $(CXX) -c $(CXXFLAGS) $< -o $@
suresh
  • 1,109
  • 1
  • 8
  • 24