Search code examples
makefileconditional-statementsrecipe

makefile conditional recipe not executing


I have a makefile which produces an executable from several object files and I include a version number in each object file as it is compiled. However, I want the version number to be incremented only when a particular object file is created (ptarget below, the one containing main). I tried to do this using a conditional statement in the recipe:

ptarget:=$(addsuffix .obj,$(ouf))

%.obj : %.cpp
    $(CXX) $(CXXFLAGS) $< -Fo$@
    $(info $(ptarget))
    $(info $@)
ifeq ($@, $(ptarget))
    perl $(perlDir)versionBump/bump.pl -inc -f $(versionFile)
endif

I can see from the info commands that only when ptarget is built that $@ == $(ptarget) -- I also tried using strip command to make sure no hidden whitespace, but the perl command to increment the version is never executed, it starts with a tab.

Just to add, this all works just fine without the conditional but the increment happens multiple times during a build, which is what I am trying to avoid. This example suggests it should work but...


Solution

  • This is a very common misunderstanding about make. ifeq is a make statement and is evaluated when make parses the Makefile. What you need is a conditional that gets evaluated when the recipe is executed by the shell, that is a shell if:

    
    %.obj : %.cpp
        $(CXX) $(CXXFLAGS) $< -Fo$@
        $(info $(ptarget))
        $(info $@)
        if [ "$@" = "$(ptarget)" ]; then \
          perl $(perlDir)versionBump/bump.pl -inc -f $(versionFile); \
        fi
    

    Do not forget the line continuations (the trailing \).