Working with multiple source file extensions in a makefile

I have a C ++ project with various extensions for source files (.cpp, .c, .cc) and various extensions for header files (.hpp, .h, .hh). The source files are in the SRC directory, and the header files are predictable in the directory named INC.

I would like to compile the source with a rule like

vpath %.c $(SRC) %.o: %.c $(COMPILER) $(FLAGS) $< $(INCFLAG)$(INC) 

This, of course, works if I know that the source file will be in the form of% .c, but in the case of several possible file extensions, I will need to create a similar rule for% .cpp and% .cc. Of course, the three rules do not really matter for writing, but it would be nice to use this make file as a drag and drop for any project, even in another language, without having to rewrite the rules.

So, how can I write a rule (or some other constructor that accomplishes the same goal) that works like:

 SRC_EXT = cpp c cc vpath %.$(SRC_EXT) $(SRC) %.o: %.$(SRC_EXT) $(COMPILER) $(FLAGS) $< $(INCFLAG)$(INC) 

Thanks for your help.

+7
source share
1 answer

You cannot use standard POSIX make. However, since you mention vpath, I assume that you are using GNU make. If you have a fairly new version (3.81 or newer), you can do this fairly easily with a call and eval:

 SRC_EXT = cpp c cc define compile_rule %.o : %.$1 $$(COMPILER) $$(FLAGS) $$< $$(INCFLAG)$$(INC) endef $(foreach EXT,$(SRC_EXT),$(eval $(call compile_rule,$(EXT)))) 

If you don't have enough new GNU make or you prefer an alternative solution, you can do the same with the generated makefiles.

+3
source

Source: https://habr.com/ru/post/906639/


All Articles