Change Makefile variable value inside the target body

前端 未结 6 1559
夕颜
夕颜 2020-12-29 00:43

Is there a way to reassign Makefile variable value inside of the target body?

What I am trying to do is to add some extra flags for debug compilation:



        
6条回答
  •  一个人的身影
    2020-12-29 01:39

    I wanted to add a target in a makefile to run tests, which implied recompiling the source code with some debug flags. Ian's answer: https://stackoverflow.com/a/15561911/ was the only solution that worked.

    Here's the Makefile I came up with, which guaranties the order of execution when running make tests:

    TARGET     = a.out
    
    CC         = g++
    GENERIC_F  = -Wall -Wextra -I. -Idoctest/doctest/
    
    CFLAGS     = -O0 -std=c++11 $(GENERIC_F)
    DEBUG_MODE = -DDEBUG
    
    LINKER     = g++
    LFLAGS     = $(GENERIC_F) -lm
    
    SRCDIR     = src
    OBJDIR     = build
    BINDIR     = bin
    
    SOURCES    = $(wildcard $(SRCDIR)/*.cc)
    INCLUDES   = $(wildcard $(SRCDIR)/*.h)
    OBJECTS    = $(SOURCES:$(SRCDIR)/%.cc=$(OBJDIR)/%.o)
    rm         = rm -f
    
    .PHONY: clear_screen tests extend_cflags
    
    $(BINDIR)/$(TARGET): $(OBJECTS) $(INCLUDES)
        $(LINKER) $(OBJECTS) $(LFLAGS) -o $@
        @echo -e "Linking complete!\n"
    
    $(OBJECTS): $(OBJDIR)/%.o : $(SRCDIR)/%.cc $(INCLUDES)
        @mkdir -p $(OBJDIR) $(BINDIR)
        $(CC) $(CFLAGS) -c $< -o $@
        @echo -e "Compiled "$<" successfully!\n"
    
    .PHONY: clean
    clean:
        @$(rm) $(OBJECTS)
        @echo "Cleanup complete!"
    
    .PHONY: remove
    remove: clean
        @$(rm) $(BINDIR)/$(TARGET)
        @echo "Executable removed!"
    
    clear_screen:
        @clear
    
    extend_cflags:
        $(eval CFLAGS += $(DEBUG_MODE))
    
    tests: | remove extend_cflags $(BINDIR)/$(TARGET) clear_screen
        @$(BINDIR)/$(TARGET)
    

提交回复
热议问题