Makefile issue: smart way to scan directory tree for .c files

后端 未结 4 977
再見小時候
再見小時候 2020-12-07 16:45

I am doing a project which is growing pretty fast and keeping the object files up date is no option. The problem beyond wildcard command lies somewhere between \"I do not wa

4条回答
  •  [愿得一人]
    2020-12-07 17:08

    I like to do the following.

    Create Variables to Each Directory of the Project

    SRCDIR = src                                                           
    OBJDIR = obj
    LIBDIR = lib
    DOCDIR = doc
    HDRDIR = include
    
    CFLAGS = -g -Wall -O3
    

    Get Only the Internal Structure of SRCDIR Recursively

    STRUCTURE := $(shell find $(SRCDIR) -type d)     
    

    Get All Files inside the STRUCTURE Variable

    CODEFILES := $(addsuffix /*,$(STRUCTURE))
    CODEFILES := $(wildcard $(CODEFILES))            
    

    Filter Out Only Specific Files

    # Filter Only Specific Files                                
    SRCFILES := $(filter %.c,$(CODEFILES))
    HDRFILES := $(filter %.h,$(CODEFILES))
    OBJFILES := $(subst $(SRCDIR),$(OBJDIR),$(SRCFILES:%.c=%.o))
    
    # Filter Out Function main for Libraries
    LIBDEPS := $(filter-out $(OBJDIR)/main.o,$(OBJFILES))
    

    Now it is Time to create the Rules

    compile: $(OBJFILES)
    
    $(OBJDIR)/%.o: $(addprefix $(SRCDIR)/,%.c %.h)
        $(CC) -c $< -o $@ $(CFLAGS) 
    

    With this approach, you can see that I'm using the STRUCTURE variable only to get the files inside the SRCDIR directory, but it can be used for others purposes as well, like mirror the SRCDIR inside OBJDIR once STRUCTURE stores only the internal sub-directories. It is quite useful after clean operations like:

    clean:
        -rm -r $(OBJDIR)/*
    

    NOTE: The compile rule only works well if for each *.c there is the corresponding *.h file (with the same base name, I mean).

提交回复
热议问题