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

后端 未结 4 978
再見小時候
再見小時候 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:10

    The simplest option to do what you want is probably to just use a shell escape and call find:

    SOURCES := $(shell find $(SOURCEDIR) -name '*.c')
    

    This gets you a list of source files with paths. Note that the use of immediate assignment := rather than recursive assignment = is important here: you do not want to be running the shell escape every time SOURCES is inspected by make (which happens a lot more than you'd think in Makefiles). A general rule I find helpful is to always use immediate assignment unless I actually need recursive expansion (which is rare; it looks like all of your assignments in this example could be immediate). This then means use of recursive assignment is also a helpful signal that the variable needs to be used carefully.

    Back to your problem. What you do next depends on whether you want a mirror of your source tree in your build tree, or whether the build dir is just supposed to contain a flat list of object files for all your source files, or whether you want a separate build dir under every source dir in the tree.

    Assuming you want the mirrored build tree, you could do something like the following:

    # Get list of object files, with paths
    OBJECTS := $(addprefix $(BUILDDIR)/,$(SOURCES:%.c=%.o))
    
    $(BINARY): $(OBJECTS)
        $(CC) $(CFLAGS) $(LDFLAGS) $(OBJECTS) -o $(BINARY)
    
    $(BUILDDIR)/%.o: %.c
        $(CC) $(CFLAGS) $(LDFLAGS) -I$(HEADERDIR) -I$(dir $<) -c $< -o $@
    

    This doesn't quite take into account the full complexity of the job, as it doesn't ensure the directories in the build tree actually exist (which would be moderately painful to do in Makefile syntax).

    I removed the -I directives from your $(BINARY) build rule; do you really need them when linking objects? The reason I didn't leave them is that you don't have just one source dir anymore, and it's non-trivial to get the list of source dirs from the list of objects (like so much in Makefile syntax it would be doable but really annoying).

提交回复
热议问题