Gmake get a list of object files from multiple directories

I do not know many makefiles that I tried to learn as needed.

The biggest drawback of my makefiles is that I listed all the files manually, while this was not a problem, my current project becomes cumbersome. I have 4 directories with source files.

How can I get the entire list of object files without specifying them manually.

This does not work, but shows what I was trying to do.

VPATH = Lib GameCode Moot/Moot Moot/Impl OBJS = $(subst .cpp, .o, $(VPATH)) foobar: $(OBJS) g++ -o $@ $^ %.o: %.cpp g++ -c $< -o $@ -I Moot clean: rm main.o lib.o foo.o foobar 
+6
makefile gnu-make
source share
2 answers

Personally, I never had problems listing all the files manually. Listing a file in a make file takes little time compared to adding content to it with useful content.

To get all the files from different directories, you can suggest using the wildcard function . Thus, my_sources:=$(wildcard *.cpp dir1/*.cpp) will force the variable to contain the source files matching the substitution expression.

However, I find this less convenient than using the usual Linux find through the shell:

 # Find all sources my_sources:=$(shell find -iname '*.cpp') # Make targets out of them OBJS=$(my_sources:%.cpp=%.o) 

Find more powerful than Make builtin wildcard . You can also use other shell features, such as pipelines, for example, to filter the find output (if the Make filter-out function is not enough). Or something like this to avoid excessive variables:

 OBJS:=$(shell find -iname '*.cpp' | sed 's/\.cpp$/.o/') 

You name it!

+5
source share

Using VPATH or vpath will not work for your problem .. it provides a search path to search for files, but you still need to list the files. If you just need to compile everything and any .c / .cpp files found in these directories, then this should work:

 foobar: $(shell ls Lib/*.cpp) $(shell ls GameCode/*.cpp) $(shell ls Moot/Moot/*.cpp) $(shell ls Moot/Impl/*cpp) g++ -o $@ $^ clean: rm foobar $(shell ls Lib/*.o) $(shell ls GameCode/*.o) $(shell ls Moot/Moot/*.o) $(shell ls Moot/Impl/*o) 

VPATH information is not needed, .o substitution for .cpp can go the same way as overriding an implicit rule. Also, not using ls instead of searching for searches and only in the specfified directory.

0
source share

All Articles