Variables in non-recursive Makefiles - makefile

I'm using GNU Make and attempting to design Makefiles using non-recursive approach. The issue I have - there doesn't seem to be a way to limit the scope of variables in different Makefiles.
For example, if I have two Makefiles for modules libA and libB
libA Makefile.inc:
src_dir := libA/src
inc_dir := libA/inc
libB Makefile.inc:
src_dir := libB/src
inc_dir := libB/inc
Then when I include the above Makefiles into a master Makefile
include libA/Makefile.inc
include libB/Makefile.inc
Values in variables src_dir and inc_dir are overwritten by the very last Makefile that was included. OK this is probably expected since variables are global in scope here, and this messes up build commands that use those variables, i.e. build command for libA finds variable values for libB.
A way around it is to create unique variables for each Makefile
libA Makefile.inc:
src_dir_libA := libA/src
inc_dir_libA := libA/inc
libB Makefile.inc:
src_dir_libB := libB/src
inc_dir_libB := libB/inc
This solves the issue, but it's a bit awkward to use, since each variable has to be renamed. Does anyone know if there is a better way to solve this, e.g. if GNU Make has some notion of scope or namespace? I've looked at documentation, but can't seem to find anything of that sort. There are target-specific variables, but they appear to have nasty side-effects.
OK, just to be very specific, below is an example Makefile
dep_all :=
all:
# Begin Makefile.inc for project1
# ------------------------------------------------------------------------------
$(foreach var,$(filter local_%,$(.VARIABLES)),$(eval $(var) := ))
local_src_dir := project1/src
local_obj_dir := project1/obj
local_src := $(local_src_dir)/fileA.c $(local_src_dir)/fileB.c
local_obj := $(patsubst $(local_src_dir)/%.c,$(local_obj_dir)/%.o,$(local_src))
dep_all += $(local_src)
dep_all += $(local_obj)
$(info local_obj="$(local_obj)")
$(local_obj): $(local_obj_dir)/%.o: $(local_src_dir)/%.c
gcc -L$(local_obj_dir) -c -o $# $<
# ------------------------------------------------------------------------------
# End Makefile.inc for project1
# Begin Makefile.inc for project2
# ------------------------------------------------------------------------------
$(foreach var,$(filter local_%,$(.VARIABLES)),$(eval $(var) := ))
local_src_dir := project2/src
local_obj_dir := project2/obj
local_src := $(local_src_dir)/fileX.c $(local_src_dir)/fileY.c
local_obj := $(patsubst $(local_src_dir)/%.c,$(local_obj_dir)/%.o,$(local_src))
dep_all += $(local_src)
dep_all += $(local_obj)
$(info local_obj="$(local_obj)")
$(local_obj): $(local_obj_dir)/%.o: $(local_src_dir)/%.c
gcc -L$(local_obj_dir) -c -o $# $<
# ------------------------------------------------------------------------------
# End Makefile.inc for project2
$(info dep_all="$(dep_all)")
.PHONY: all
all: $(dep_all)
.PHONY: clean
clean:
rm -f project1/obj/* project2/obj/*
If I run it then the -L<object_path> option passed to gcc contains value from the last included Makefile, i.e. when building project1, it runs gcc with -Lproject2/obj, which is not the right object path for this project. This is the problem I'm trying to solve.
mkdir -p project1/{src,obj} project2/{src,obj}
touch project1/src/{fileA.c,fileB.c} project2/src/{fileX.c,fileY.c}
$ make
local_obj="project1/obj/fileA.o project1/obj/fileB.o"
local_obj="project2/obj/fileX.o project2/obj/fileY.o"
dep_all=" project1/src/fileA.c project1/src/fileB.c project1/obj/fileA.o project1/obj/fileB.o project2/src/fileX.c project2/src/fileY.c project2/obj/fileX.o project2/obj/fileY.o"
gcc -Lproject2/obj -c -o project1/obj/fileA.o project1/src/fileA.c
gcc -Lproject2/obj -c -o project1/obj/fileB.o project1/src/fileB.c
gcc -Lproject2/obj -c -o project2/obj/fileX.o project2/src/fileX.c
gcc -Lproject2/obj -c -o project2/obj/fileY.o project2/src/fileY.c

The solution is to name all your variables local to a specific file with some prefix.
For example, I use this_ prefix.
Then, in the beginning of each submakefile those variales which have this_ prefix can be cleared as follows:
$(foreach var,$(filter this_%,$(.VARIABLES)),$(eval $(var) := ))
PS. I use this approach in my implementation of non-recursive makefiles, clearing the variables described in the WIKI here: https://github.com/cppfw/prorab

I think I've just figured out a solution. I was reading "The GNU Make Book" and it states a side effect of target specific variables
Target-specific variables apply not just to a target, but also to all
that target’s prerequisites, as well as all their prerequisites, and
so on. A target-specific variable’s scope is the entire tree of
targets, starting from the target for which the variable was defined.
This is not the behaviour I want, however starting with GNU Make 3.82 there is support for private target specific variables
A target-specific variable is normally defined for a target and all
its prerequisites. But if the target-specific variable is prefixed
with the keyword private, it is defined only for that target, not its
prerequisites.
So the following Makefile seems to work correctly for those private variables
dep_all :=
all:
# Begin Makefile.inc for project1
# ------------------------------------------------------------------------------
inc_dir := project1/inc
src_dir := project1/src
obj_dir := project1/obj
src := $(src_dir)/fileA.c $(src_dir)/fileB.c
obj := $(patsubst $(src_dir)/%.c,$(obj_dir)/%.o,$(src))
# These flags will be overwritten by another Makefile
CFLAGS := -I$(inc_dir)
# These flags will be private and not be overwritten by another Makefile
CFLAGS_priv := -I$(inc_dir) -L$(obj_dir)
dep_all += $(src)
dep_all += $(obj)
# Private target specific variables
$(obj): private CFLAGS_priv:=$(CFLAGS_priv)
$(obj): $(obj_dir)/%.o: $(src_dir)/%.c
gcc $(CFLAGS) $(CFLAGS_priv) -c -o $# $<
# ------------------------------------------------------------------------------
# End Makefile.inc for project1
# Begin Makefile.inc for project2
# ------------------------------------------------------------------------------
inc_dir := project2/inc
src_dir := project2/src
obj_dir := project2/obj
src := $(src_dir)/fileX.c $(src_dir)/fileY.c
obj := $(patsubst $(src_dir)/%.c,$(obj_dir)/%.o,$(src))
# These flags will be overwritten by another Makefile
CFLAGS := -I$(inc_dir)
# These flags will be private and not be overwritten by another Makefile
CFLAGS_priv := -I$(inc_dir) -L$(obj_dir)
dep_all += $(src)
dep_all += $(obj)
# Private target specific variables
$(obj): private CFLAGS_priv:=$(CFLAGS_priv)
$(obj): $(obj_dir)/%.o: $(src_dir)/%.c
gcc $(CFLAGS) $(CFLAGS_priv) -c -o $# $<
# ------------------------------------------------------------------------------
# End Makefile.inc for project2
.PHONY: all
all: $(dep_all)
.PHONY: clean
clean:
rm -f project1/obj/* project2/obj/*
The output is what I wanted, since now for each project I can define private CFLAGS_priv variable that sets -I<dir>, -L<dir> paths and it won't be overwritten by other Makefiles.
$ make
gcc -Iproject2/inc -Iproject1/inc -Lproject1/obj -c -o project1/obj/fileA.o project1/src/fileA.c
gcc -Iproject2/inc -Iproject1/inc -Lproject1/obj -c -o project1/obj/fileB.o project1/src/fileB.c
gcc -Iproject2/inc -Iproject2/inc -Lproject2/obj -c -o project2/obj/fileX.o project2/src/fileX.c
gcc -Iproject2/inc -Iproject2/inc -Lproject2/obj -c -o project2/obj/fileY.o project2/src/fileY.c
I'm hoping this will resolve all issues I had and I don't have to use recursive make with it's various associated pitfalls.

Related

No rule to make target error output while building C project using GNU Make

I am trying to build a dummy C project using GNU Make. I use the following rules to build the object files from the c files and the output from the object files :
AT := #
#Initial tools to get the absolute paths.
TOOLSDIR := ./tools/bin
SHELL := $(TOOLSDIR)/sh
CYGPATH := $(TOOLSDIR)/cygpath
# Defining used tools
TOOLSDIR := $(shell $(CYGPATH) -am "$(TOOLSDIR)")
SCRIPTDIR := $(shell $(CYGPATH) -am "$(SCRIPTDIR)")
LIBDIR := $(shell $(CYGPATH) -am "$(LIBDIR)")
#Defining Env Variable responsible for Removing non-ansi characters in error output
LC_ALL=C
SHELL := $(shell $(CYGPATH) -am "$(SHELL)")
CYGPATH := $(shell $(CYGPATH) -am "$(CYGPATH)")
TEST := $(shell $(CYGPATH) -am "$(TOOLSDIR)/test")
RM := $(shell $(CYGPATH) -am "$(TOOLSDIR)/rm") -f
PERL := $(shell $(CYGPATH) -am "$(TOOLSDIR)/perl")
FIND := $(shell $(CYGPATH) -am "$(TOOLSDIR)/find")
MKDIR := $(shell $(CYGPATH) -am "$(TOOLSDIR)/mkdir")
PERL5LIB := $(LIBDIR)/perl5/site_perl/5.14/x86_64-cygwin-threads;$(LIBDIR)/perl5/site_perl/5.14;$(LIBDIR)/perl5/5.14/x86_64-cygwin-threads;$(LIBDIR)/perl5/5.14
# Defining perl script to convert dependencies genereted by the compiler to unix path
FIXDEPS_SCRIPT := "$(SCRIPTDIR)/fixdeps.pl"
ZAPEXEC_SCRIPT := "$(SCRIPTDIR)/ZAP_Command.pl"
DEPFIX := $(PERL) $(FIXDEPS_SCRIPT)
ZAPEXE := $(PERL) $(ZAPEXEC_SCRIPT)
CREATE_IAR_PROJ := $(PERL) $(IARWKSP_SCRIPT)
COMP_DIR :=C:\ghs\comp_201355
OBJDIR :=.
CC := "$(COMP_DIR)/ccrh850.exe"
AS := "$(COMP_DIR)/ccrh850.exe"
LD := "$(COMP_DIR)/ccrh580.exe"
GSREC := "$(COMP_DIR)/gsrec.exe"
GMEM := "$(COMP_DIR)/gmemfile.exe"
CEXT :=c
CCEXT :=C
ASMEXTC := S
ASMEXTS := s
ASMEXT := 850
ASMEXT_DEFAULT := asm
DBGEXT := dla
DBGEXT_DEFAULT := dnm
OBJEXT := o
EXEEXT := elf
LSTEXT := lst
DEPEXT := dd
INCOPT := -I
EXEMAP := ./exe/PROJECT_NAME.map
CFLAGS :=-c -G -Onone -no_callt -sda=all -large_sda -reserve_r2 -Wundef --short_enum -dual_debug \
-delete -preprocess_assembly_files --no_wrap_diagnostics -registermode=32 -keeptempfiles -prepare_dispose -ansi \
-full_debug_info -noobj -Wimplicit-int -Wshadow -Wtrigraphs -inline_prologue -DOS_MEMMAP=0 -DOS_MULTICORE=OS_SINGLE \
-DOS_USE_CLZ_QUEUE_ALGORITHM=1 -DOS_DEVELOPMENT_SANITY_CHECKS=0 -DOS_KERNEL_TYPE=OS_FUNCTION_CALL -DOS_USE_TRACE=0 -MD \
-DAUTOSAR_USED -DRENESAS -DF1K -DR7F701583xAFP --long_long -cpu=rh850 -DTS_ARCH_FAMILY=TS_RH850 \
-DTS_ARCH_DERIVATE=TS_RH850F1L -DRH850F1L=1 -DOS_CPU=OS_RH850F1L -DOS_TOOL=OS_ghs -DOS_ARCH=OS_RH850
VPATH :=./ ./obj ./src ./exe
INCLUDES :=-I"./" -I"./obj" -I"./src" -I"./exe"
OBJECTS :=./obj/main.o
.PHONY: all release debug
EXEC := ./exe/PROJECT_NAME.hex
EXEOUT := ./exe/PROJECT_NAME.out
all: debug release
release: $(EXEC)
debug: release
$(EXEC): $(EXEOUT)
#echo '************************************'
#echo 'Using GSREC to Convert .out to .hex'
$(AT)$(GSREC) -o$(EXEC) $(EXEOUT)
#echo 'Generation Done'
#echo '************************************'
$(EXEOUT): $(OBJECTS)
#echo '************************************'
#echo 'Building .out file'
#echo $(EXEOUT)
$(AT)$(CC) $(LDFLAGS) -o $(EXEOUT) $(OBJECTS)
#echo '************************************'
$(OBJDIR)/%.$(OBJEXT): %.$(CEXT)
#echo 'Compiling: $<'
$(AT)$(CC) $(CFLAGS) $(INCLUDES) -filetype.c $(shell $(CYGPATH) -am "$<") -o $#
The output when I execute the target all is as follows :
make: *** No rule to make target 'obj/main.o', needed by 'exe/PROJECT_NAME.out'. Stop.
The main.c source file has the following code :
#include <stdio.h>
#include <stdlib.h>
#include "alpha.c"
void second(void);
int main()
{
printf("Second module, I send you greetings!n");
second();
return 0;
}
The alpha.c source file has the following code :
#include <stdio.h>
void second(void)
{
puts("Glad to be here!");
}
Where $(OBJECTS) is the relative path of all the object files that are supposed to be generated and $(EXEC) and $(EXEOUT) are the outputs. The VPATH contains relative paths. All the needed prerequisites (.c and.h files) can be found among the paths in VPATH and in INCLUDES in the compilation command. That is the exact code I use to build this dummy project which contains only two .c files main.c and alpha.c and main.c uses alpha.c. When the source files are in the same folder as the makefile this dummy project builds, but when I put the source files in the src folder and create a obj folder for the object files to be generated in and an exe folder for the final output to be generated in previously mentioned error appears. What could be the reason for the previously mentioned error?
#Beta is right that it's generally a bad idea to dump a huge makefile into StackOverflow and ask someone to fix it. You should instead try to reduce the problem as much as possible.
However in this case, your problem is here:
OBJDIR :=.
OBJECTS :=./obj/main.o
$(EXEOUT): $(OBJECTS)
...
$(OBJDIR)/%.$(OBJEXT): %.$(CEXT)
...
So after all the variables have been expanded, you get these rules:
./exe/PROJECT_NAME.out: ./obj/main.o
...
./%.o: %.c
...
Well, when make tries to match the pattern ./%.o with the target to be built ./obj/main.o, the stem % will match obj/main. Then it will try to find %.c which resolves to obj/main.c, which doesn't exist.
You should be using the OBJDIR variable in your OBJECTS variable assignment, like:
OBJECTS :=$(OBJDIR)/main.o
then it will work.

Makefile wildcard for makefile variables, to define generic rules

Background, I suspect XY problem
I have simpler C modules in a directory. I want to write unit tests for these in a sub-directory test/. These unit tests are no more than C programs linking to the module under test, one directory above. I want a Makefile that defines several build targets and lets me build and run the test executables in one step, or separately.
My attempted solution
I've attempted the following:
CC = gcc
CFLAGS = -ggdb -Wall -Wextra -Werror -O3 -std=c99
PARAM_LIST_TARGET = parameter_list_test
PARAM_LIST_SOURCE_FILES = \
../parameter_list.c \
parameter_list_test.c
PARAM_LIST_OBJECT_FILES := $(addsuffix .o,$(basename $(PARAM_LIST_SOURCE_FILES)))
TARGETS = $(PARAM_LIST_TARGET)
all: $(TARGETS)
$(%_TARGET): $(%_OBJECT_FILES)
$(CC) $(CFLAGS) $^ -o $#
.c.o:
$(CC) -c $< -o $# $(CFLAGS)
clean:
$(RM) *.o $(TARGETS)
test: all
#for t in $(TARGETS) ; do ./$$t ; done
This doesn't work, and it's because of the $(%_TARGET): row. Not surprising, I didn't expect it to work, but I hope this illustrates what I'm trying to achieve.
I want to create more chunks of the form _TARGET, _SOURCE_FILES, and _OBJECT_FILES, to test other modules besides PARAM_LIST, for example:
PARAM_LIST_TARGET = parameter_list_test
PARAM_LIST_SOURCE_FILES = \
../parameter_list.c \
parameter_list_test.c
PARAM_LIST_OBJECT_FILES := $(addsuffix .o,$(basename $(PARAM_LIST_SOURCE_FILES)))
OTHER_MODULE_TARGET = other_module_test
OTHER_MODULE_SOURCE_FILES = \
../other_module.c \
other_module_test.c
OTHER_MODULE_OBJECT_FILES := $(addsuffix .o,$(basename $(OTHER_MODULE_SOURCE_FILES)))
I understand that % works on filenames, so attempting to use it on variables fails:
$(%_TARGET): $(%_OBJECT_FILES)
$(CC) $(CFLAGS) $^ -o $#
How can I write a rule that matches the Makefile variables _TARGET to their associated _OBJECT_FILES, without creating one per test target?
Or more importantly, how should I do it totally differently?
Edit: I've seen this, however it seems it's only working with a single source file per executable.
You can always access make variables by constructing their names:
MY_VAR := "my var"
HIS_VAR := "his var"
HER_VAR := "her var"
CATS_VAR := "cats var"
DOGS_VAR := "dogs var"
ALL_PERSONS := MY HIS HER CATS DOGS
ALL_VARS := $(foreach p,$(ALL_PERSONS),$($(p)_VAR))
$(info $(ALL_VARS))
Output:
$ make
"my var" "his var" "her var" "cats var" "dogs var"
Defining the dependencies separately seems to work, thanks to this answer:
TARGETS = $(PARAM_LIST_TARGET) $(OTHER_MODULE_TARGET)
all: $(TARGETS)
$(PARAM_LIST_TARGET): $(PARAM_LIST_OBJECT_FILES)
$(OTHER_MODULE_TARGET): $(OTHER_MODULE_OBJECT_FILES)
$(TARGETS):
$(CC) $(CFLAGS) $^ -o $#
This eliminates the need for a duplicate rule (one per target). Still, the definition of dependencies for each target looks like duplicates, a pattern match for these would be nice.
More than that, the OBJECT_FILES variable becomes unnecessary. This works:
PARAM_LIST_TARGET = parameter_list_test
PARAM_LIST_SOURCE_FILES = \
../parameter_list.c \
parameter_list_test.c
$(PARAM_LIST_TARGET): $(addsuffix .o,$(basename $(PARAM_LIST_SOURCE_FILES))) # The dependencies directly
It would still feel nice to have this last row as one rule for all targets. Something like "for all variables ending with TARGET, build a dependency to the content of the variable with the same name, but ending with SOURCE_FILES instead".

GNU Make correct behaviour when including other makefiles

I have the following makefile in the root of the project:
Makefile
# Board version
# Available: 3
PI ?= 3
# Kernel binaries
ifeq ($(PI), 3)
KERNEL_IMG := kernel8.img
else ifeq ($(PI), 2)
KERNEL_IMG := kernel7.img
else ifeq ($(PI), 1)
KERNEL_IMG := kernel.img
else
$(error Unsupported Raspberry Pi version)
endif
KERNEL_ELF := $(patsubst %.img,%.elf,$(KERNEL_IMG))
# Directories/paths
BUILD_DIR := build
# Toolchain
TOOLCHAIN ?= aarch64-elf
OBJCOPY := $(TOOLCHAIN)-objcopy
LD := $(TOOLCHAIN)-ld
CC := $(TOOLCHAIN)-gcc
# Misc
LINKER_SCRIPT := linker.ld
# Flags
LDFLAGS := -T $(LINKER_SCRIPT)
ASFLAGS :=
CFLAGS :=
# Source files
C_SRC := $(wildcard *.c)
ASM_SRC := $(wildcard *.S)
# Include
include pi/$(PI)/mod.mk
# Object files
OBJECTS := $(patsubst %,$(BUILD_DIR)/%.o,$(C_SRC))
OBJECTS += $(patsubst %,$(BUILD_DIR)/%.o,$(ASM_SRC))
# Targets
.PHONY: all builddirs clean
all: $(BUILD_DIR)/$(KERNEL_IMG)
$(BUILD_DIR)/$(KERNEL_IMG): $(BUILD_DIR)/$(KERNEL_ELF)
$(OBJCOPY) $< -O binary $#
$(BUILD_DIR)/$(KERNEL_ELF): $(LINKER_SCRIPT) $(OBJECTS)
$(LD) $(OBJECTS) $(LDFLAGS) -o $#
$(OBJECTS): | builddirs
builddirs: $(BUILD_DIR)/pi/$(PI)
$(BUILD_DIR)/pi/$(PI):
mkdir -p $#
$(BUILD_DIR)/%.S.o: %.S
$(CC) -c $< $(ASFLAGS) -o $#
$(BUILD_DIR)/%.c.o: %.c
$(CC) -c $< $(CFLAGS) -o $#
clean:
$(RM) -r $(BUILD_DIR)
It includes pi/3/mod.mk
C_SRC +=
ASM_SRC += pi/3/start.S
$(BUILD_DIR)/pi/3/start.S.o: pi/3/start.S pi/3/include/cpu/sysregs.h
$(CC) -c $< $(ASFLAGS) -o $#
Now here's the problem: whenever I run 'make' in the root of a project, '$(BUILD_DIR)/pi/3/start.S.o' rule invokes, instead of 'all'. If I move 'include pi/$(PI)/mod.mk' to the very bottom of the root makefile, and replace 'C_SRC' and 'ASM_SRC' variables in 'pi/3/mod.mk' with 'OBJECTS += $(BUILD_DIR)/pi/3/start.S.o' and invoke 'make', this rule isn't even invoked, so I get an error that make doesn't know how to build start.S.o.
What am I doing wrong and what is the best way to handle this?
Make's default goal is the first target in your Makefile. In your case the first target is the one defined in the included Makefile: $(BUILD_DIR)/pi/3/start.S.o. Either invoke make all or move the all rule in your Makefile such that it becomes the first one, or tell make that the default goal is all:
.DEFAULT_GOAL := all
(see GNU make manual).

Outputting obj files to obj directory in Makefile

Hi I wrote this Makefile by modifying this example: https://sites.google.com/site/michaelsafyan/software-engineering/how-to-write-a-makefile
program_NAME := bin/myprogram
SRC_DIR := src
#
#srces
#
program_C_SRCS := $(wildcard $(SRC_DIR)/*.c)
program_CXX_SRCS := $(wildcard $(SRC_DIR)/*.cpp)
#
#obj files
#
program_C_OBJS := ${program_C_SRCS:.c=.o}
program_CXX_OBJS := ${program_CXX_SRCS:.cpp=.o}
program_OBJS := $(program_C_OBJS) $(program_CXX_OBJS)
#
# include and library dirs; also libraries
#
program_INCLUDE_DIRS := inc
program_LIBRARY_DIRS :=
program_LIBRARIES :=
# flags
CPPFLAGS += $(foreach includedir,$(program_INCLUDE_DIRS),-I$(includedir))
LDFLAGS += $(foreach librarydir,$(program_LIBRARY_DIRS),-L$(librarydir))
LDFLAGS += $(foreach library,$(program_LIBRARIES),-l$(library))
#
# targets
#
.PHONY: all clean distclean
all: $(program_NAME)
$(program_NAME): $(program_OBJS)
$(LINK.cc) $(program_OBJS) -o $(program_NAME)
clean:
#- $(RM) $(program_NAME)
#- $(RM) $(program_OBJS)
distclean: clean
It works in the following way. The classes below are compiled into an executable "myprogram" which is output in the bin directory. The only issue is the object files are created inside the src folder, instead of the obj folder. How can I modify this makefile such that obj files are created in the obj folder? Thank you.
/project
Makefile
/src
Class1.cpp
Class2.cpp
main.cpp
/obj
/bin
myProgram
/inc
Class1.h
Class2.h
To start with, you could use e.g. the subst function to replace the source-file directory with the object-file directory:
program_OBJS = $(subst $(SRC_DIR),$(OBJ_DIR),$(program_C_OBJS))
program_OBJS += $(subst $(SRC_DIR),$(OBJ_DIR),$(program_CXX_OBJS))
Of course you now need to add a target for object-file creation, as these will not be put in the correct place otherwise:
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
$(CC) $(CFLAGS) -c -o $# $<
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
$(CXX) $(CXXFLAGS) -c -o $# $<
Try with something like:
OUT_DIR=obj
program_bare_OBJS := $(program_C_OBJS) $(program_CXX_OBJS)
program_OBJS=$(addprefix $(OUT_DIR)/,$(program_bare_OBJS))

Problem creating gnu makefile "function"

I have a big chunk of my makefile (~50 lines) that needs to be copy-pasted 5 times for different case (the different libraries used). Is it possible to create a function in a makefile and just call that function instead of copy-pasting?
This is an example of what I've tried. Basically this tries to find the right path for an installed library.
define Flags_template
$(1)_include_home := $(HOME)/usr/include
$(1)_include_home_name := $(HOME)/usr/include/$(1)
ifneq ($$(wildcard $($(1)_include_home)/$(2)),)
$(1)_Include := $$($(1)_include_home)
else
ifneq ($$(wildcard $($(1)_include_home_name)/$(2)),)
$(1)_Include := $$($(1)_include_home_name)
endif
endif
CFLAGS += -I$$($(1)_Include)
endef
$(eval $(call Flags_template,stdcout,StdCout.hpp))
.PHONY: test
test:
# stdcout_include_home_name = $(stdcout_include_home_name)
# stdcout_Include = $(stdcout_Include)
# CFLAGS: $(CFLAGS)
Typing "make", I get this output:
# stdcout_include_home_name = /home/nicolas/usr/include/stdcout
# stdcout_Include =
# CFLAGS: -I
It's so close. But note the last "-I", I always get dupplicates, one fully expended, one empty...
I don't understant what needs to be eval'ed, escaped with two $, etc.
How can I achieve this?
Thank you very much.
Does §8.8 of the GNU Make (3.82) manual help?
[...] Although it might seem overly complex to use eval in this example,
rather than just writing out the rules, consider two things: first, the template definition (in
PROGRAM_template) could need to be much more complex than it is here; and second, you
might put the complex, “generic” part of this example into another makefile, then include
it in all the individual makefiles. Now your individual makefiles are quite straightforward.
PROGRAMS = server client
server_OBJS = server.o server_priv.o server_access.o
server_LIBS = priv protocol
client_OBJS = client.o client_api.o client_mem.o
client_LIBS = protocol
# Everything after this is generic
.PHONY: all
all: $(PROGRAMS)
define PROGRAM_template =
$(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
ALL_OBJS += $$($(1)_OBJS)
endef
$(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
$(PROGRAMS):
$(LINK.o) $^ $(LDLIBS) -o $#
clean:
rm -f $(ALL_OBJS) $(PROGRAMS)
This Works (For Me)
This is the output from the GNU makefile just below:
stdcout_include_home = /work4/jleffler/usr/include
stdcout_include_home_name = /work4/jleffler/usr/include/stdcout
stdcout_Include = /work4/jleffler/usr/include
CFLAGS: -I/work4/jleffler/include -I/work4/jleffler/usr/include
GNU Makefile
CFLAGS = -I${HOME}/include
define Flags_template
$(1)_include_home := $(HOME)/usr/include
$(1)_include_home_name := $(HOME)/usr/include/$(1)
ifneq ($$(wildcard $$($(1)_include_home)/$(2)),)
$(1)_Include := $$($(1)_include_home)
else
ifneq ($$(wildcard $$($(1)_include_home_name)/$(2)),)
$(1)_Include := $$($(1)_include_home_name)
else
$(1)_Include := Neither $$($(1)_include_home) nor $$($(1)_include_home_name) contains $2
endif
endif
CFLAGS += -I$$($(1)_Include)
endef
$(eval $(call Flags_template,stdcout,StdCout.hpp))
.PHONY: test
test:
#echo stdcout_include_home = $(stdcout_include_home)
#echo stdcout_include_home_name = $(stdcout_include_home_name)
#echo stdcout_Include = $(stdcout_Include)
#echo CFLAGS: $(CFLAGS)
The difference is in the wildcard invocations:
ifneq ($$(wildcard $($(1)_include_home)/$(2)),) # Fails
ifneq ($$(wildcard $$($(1)_include_home)/$(2)),) # Works
I have half an intuition about when double-dollars and when single-dollars are needed; I am not sure I can articulate the decision, though.

Resources