How can I configure my makefile for debug and release builds?

后端 未结 7 571
借酒劲吻你
借酒劲吻你 2020-12-12 08:41

I have the following makefile for my project, and I\'d like to configure it for release and debug builds. In my code, I have lots of #ifdef DEBUG macros in plac

7条回答
  •  时光说笑
    2020-12-12 09:33

    This question has appeared often when searching for a similar problem, so I feel a fully implemented solution is warranted. Especially since I (and I would assume others) have struggled piecing all the various answers together.

    Below is a sample Makefile which supports multiple build types in separate directories. The example illustrated shows debug and release builds.

    Supports ...

    • separate project directories for specific builds
    • easy selection of a default target build
    • silent prep target to create directories needed for building the project
    • build-specific compiler configuration flags
    • GNU Make's natural method of determining if project requires a rebuild
    • pattern rules rather than the obsolete suffix rules

    #
    # Compiler flags
    #
    CC     = gcc
    CFLAGS = -Wall -Werror -Wextra
    
    #
    # Project files
    #
    SRCS = file1.c file2.c file3.c file4.c
    OBJS = $(SRCS:.c=.o)
    EXE  = exefile
    
    #
    # Debug build settings
    #
    DBGDIR = debug
    DBGEXE = $(DBGDIR)/$(EXE)
    DBGOBJS = $(addprefix $(DBGDIR)/, $(OBJS))
    DBGCFLAGS = -g -O0 -DDEBUG
    
    #
    # Release build settings
    #
    RELDIR = release
    RELEXE = $(RELDIR)/$(EXE)
    RELOBJS = $(addprefix $(RELDIR)/, $(OBJS))
    RELCFLAGS = -O3 -DNDEBUG
    
    .PHONY: all clean debug prep release remake
    
    # Default build
    all: prep release
    
    #
    # Debug rules
    #
    debug: $(DBGEXE)
    
    $(DBGEXE): $(DBGOBJS)
        $(CC) $(CFLAGS) $(DBGCFLAGS) -o $(DBGEXE) $^
    
    $(DBGDIR)/%.o: %.c
        $(CC) -c $(CFLAGS) $(DBGCFLAGS) -o $@ $<
    
    #
    # Release rules
    #
    release: $(RELEXE)
    
    $(RELEXE): $(RELOBJS)
        $(CC) $(CFLAGS) $(RELCFLAGS) -o $(RELEXE) $^
    
    $(RELDIR)/%.o: %.c
        $(CC) -c $(CFLAGS) $(RELCFLAGS) -o $@ $<
    
    #
    # Other rules
    #
    prep:
        @mkdir -p $(DBGDIR) $(RELDIR)
    
    remake: clean all
    
    clean:
        rm -f $(RELEXE) $(RELOBJS) $(DBGEXE) $(DBGOBJS)
    

提交回复
热议问题