Make one (or more) template files that you put in a common base folder, then in each project directory place a makefile which sets flags specific to the library being built, as well as listing only the source files. Then it includes the common makefile(s) templates, which contains implicit rules and variables that takes the local flags for building.
So a structure something like this:
project root
|-- makefiles
| |-- rules.mk
| |-- vars.mk
| |-- exe.mk
| `-- lib.mk
|-- libraryA
| |-- Makefile
| `-- (other sources and headers for this library)
|-- libraryB
| |-- Makefile
| `-- (other sources and headers for this library)
|-- programA
| |-- Makefile
| `-- (other sources and headers for this program)
`-- programB
|-- Makefile
`-- (other sources and headers for this program)
The rules.mk
contains rules such as clean
or the implicit build rules like .c.o
.
The vars.mk
contains global variables and uses local flag variables to set the global flag variables like CFLAGS
.
The exe.mk
contains rules to make an executable program.
The lib.mk
contains rules to make a library.
A local makefile will then look something like this:
LOCAL_CFLAGS = <some C flags specific to just this library/executable>
# Other local flags, e.g. LOCAL_LDFLAGS, LOCAL_LIBS, etc.
TARGET = <name of target executable/library>
LOCAL_SOURCES = <list of all source files for $(TARGET)>
LOCAL_HEADERS = <list of all headers>
include ../makefiles/vars.mk
include ../makefiles/rules.mk
include ../makefiles/exe.mk # If making an executable
include ../makefiles/lib.mk # If making a library
# Note: Don't include both the above two files
The vars.mk
file can look something like this
CFLAGS = <some common C flags>
CFLAGS += $(LOCAL_CFLAGS)
# All other flag variables
HEADERS = $(LOCAL_HEADERS)
CFILES = $(filter %.c,$(LOCAL_SOURCES))
CXXFILES = $(filter %.cpp,$(LOCAL_SOURCES))
OBJECTS = $(CFILES:%.c=%.o)
OBJECTS += $(CFILES:%.cpp=%.o)