Call gnumake on all subdirs in parallel (-j) and only then run the linker-rule last (i.e. order important) - c++

I have a c++ makefile project. It works great for non-parallel building. It works 99% for parallel building... the only problem I have is that I can't get my final executable link-line to run last (it must be the last thing that happens).
I have some constraints: I don't want to have any PHONY dependencies on my link line because this causes it to re-link every time. I.e. once my target is built, when I re-build it should not be re-linked.
Here is (slightly contrived) minimal example. Please don't try to pick holes in it, its really here just to show the problem, its not real, but the problem I am showing is. You should be able to just run this and see the same issue that I am.
# Set the default goal to build.
.DEFAULT_GOAL = build
#pretend subdirs (these don't really exist but it does not matter so long as they always try to be built)
MAKE_SUB_DIRS = 1 2 3
#pretend shared objects that are created by the pretend makefile sub directories (above)
OUTPUTS = out1.so out2.so out3.so
# Top level build goal - depends on all of the subdir makes and the target.out
.PHONY: build
build: $(MAKE_SUB_DIRS) target.out
#echo build finished
# Takes 1 second to build each of these pretend sub make directories. PHONY so always runs
.PHONY: $(MAKE_SUB_DIRS)
$(MAKE_SUB_DIRS):
#if [ ! -f out$#.so ] ; then echo making $#... ; sleep 1 ; echo a > out$#.so ; fi
# The main target, pretending that it needs out1,2 and 3 to link
# Should only run when target.out does not exist
# No PHONY deps allowed here
target.out:
#echo linking $#...
#ls $(OUTPUTS) > /dev/null
#cat $(OUTPUTS) > target.out
# Clean for convinience
clean:
#rm -rf *.so target.out
Now, I don't really care about make working, what I want is make -j to work. Here is me trying to run it:
admin#osboxes:~/sandbox$ make clean
admin#osboxes:~/sandbox$
admin#osboxes:~/sandbox$ make -j - 1st attempt
making 1...
making 2...
linking target.out...
making 3...
ls: cannot access 'out1.so': No such file or directory
ls: cannot access 'out2.so': No such file or directory
ls: cannot access 'out3.so': No such file or directory
makefile:24: recipe for target 'target.out' failed
make: *** [target.out] Error 2
make: *** Waiting for unfinished jobs....
admin#osboxes:~/sandbox$
admin#osboxes:~/sandbox$ make -j - 2nd attempt
linking target.out...
build finished
admin#osboxes:~/sandbox$
admin#osboxes:~/sandbox$ make -j - 3rd attempt
build finished
admin#osboxes:~/sandbox$
So I highlighted my three attempts to run it.
Attempt 1: you can see all 4 dependencies of build are started at the same time (approx). Since each of the makeing x... take 1 second and the linking is nearly instant we see my error. However all the three "libraries" are build correctly.
Attempt 2: The libraries only get created if they don't already exists (that's bash code - pretending to do what a makefile might have done). In this case they are already created. So the Linking passes now since it just requires the libraries to exist.
Attempt 3: nothing happens because nothing needs to :)
So you can see all the steps are there, its simply a matter of ordering them. I would like the the make sub dirs 1, 2, 3 to build in any order in parallel and then only once they are all completed I want target.out to run (i.e. the linker).
I don't want to call it like this though: $(MAKE) target.out because in my real makefile I have lots of variables all setup...
I have tried looking at (from othe answers) .NOT_PARALLEL and using the dep order operator | (pipe), and I have tried order a load of rules to get target.out to be last.... but the -j option just ploughs through all of these and ruins my ordering :( ... there must be some simple way to do this?

EDIT: add an example of ways to pass variables to sub-makes. Optimized a bit by adding $(SUBDIRS) to the prerequisites of build instead of making them in its recipe.
I am not sure I fully understand your organization but one solution to deal with sub-directories is as follows. I assume, a bit like in your example, that building sub-directory foo produces foo.o in the top directory. I assume also that your top Makefile defines variables (VAR1, VAR2...) that you want to pass to the sub-makes when building your sub-directories.
VAR1 := some-value
VAR2 := some-other-value
...
SUBDIRS := foo bar baz
SUBOBJS := $(patsubst %,%.o,$(SUBDIRS))
.PHONY: build clean $(SUBDIRS)
build: $(SUBDIRS)
$(MAKE) top
$(SUBDIRS):
$(MAKE) -C $# VAR1=$(VAR1) VAR2=$(VAR2) ...
top: top.o $(SUBOBJS)
$(CXX) $(LDFLAGS) -o $# $^ $(LDLIBS)
top.o: top.cc
$(CXX) $(CXXFLAGS) -c $< -o $#
clean:
rm -f top top.o $(SUBOBJS)
for d in $(SUBDIRS); do $(MAKE) -C $$d clean; done
This is parallel safe and guarantees that the link will take place only after all sub-builds complete. Note that you can also export the variables you want to pass to sub-makes, instead of passing them on the command line:
VAR1 := some-value
VAR2 := some-other-value
...
export VAR1 VAR2 ...

Normally you would just add the lib files as prerequisites of target.out:
target.out: $(OUTPUTS)
#echo linking $#...
The thing is, this will relink target.out if any of the output lib files are newer. Normally this is what you want (if the lib has changed, you need to relink target), but you specifically say you do not.
GNU make provides an extension called "order only prerequisites", which you put after a |:
target.out: | $(OUTPUTS)
#echo linking $#...
now, target.out will only be relinked if it does not exist, but in that case, it will still wait until after $(OUTPUTS) have finished being built
If your $(OUTPUT) files are build by subsirectory makes, you may find you need a rule like:
.PHONY: $(OUTPUT)
$(OUTPUT):
$(MAKE) -C $$(dirname $#) $#
to invoke the recursive make, unless you have other rules that will invoke make in the subdirectories

Ok, so I have found "a" solution... but it goes a little bit against what I wanted and is therefore ugly (but not that that ugly):
The only way I can fathom to ensure order in parallel build (again from other answers I read) is like this:
rule: un ordered deps
rule:
#echo this will happen last
Here the three deps will be made (or maked?) in any order and then finally the echo line will be run.
However the thing that I want to do is a rule and specifically so, such that it checks if anything has changed or if the file does not exist - and then, and only then, runs the rule.
The only way I know of to run a rule from within the bode of another rule is to recursively call make on it. However I get the following issues just calling make recursively on the same makefile:
Variables are not passed in by default
Many of the same rules will be re-defined (not allowed or wanted)
So I came up with this:
makefile:
# Set the default goal to build.
.DEFAULT_GOAL = build
#pretend subdirs (these don't really exist but it does not matter so long as they always try to be built)
MAKE_SUB_DIRS = 1 2 3
#pretend shared objects that are created by the pretend makefile sub directories (above)
OUTPUTS = out1.so out2.so out3.so
# Top level build goal - depends on all of the subdir makes and the target.out
export OUTPUTS
.PHONY: build
build: $(MAKE_SUB_DIRS)
#$(MAKE) -f link.mk target.out --no-print-directory
#echo build finished
# Takes 1 second to build each of these pretend sub make directories. PHONY so always runs
.PHONY: $(MAKE_SUB_DIRS)
$(MAKE_SUB_DIRS):
#if [ ! -f out$#.so ] ; then echo making $#... ; sleep 1 ; echo a > out$#.so ; fi
# Clean for convinience
clean:
#rm -rf *.so target.out
link.mk:
# The main target, pretending that it needs out1,2 and 3 to link
# Should only run when target.out does not exist
# No PHONY deps allowed here
target.out:
#echo linking $#...
#ls $(OUTPUTS) > /dev/null
#cat $(OUTPUTS) > target.out
So here I put the linker rule into a separate makefile called link.mk, this avoids recursive make calling on the same file (and therefore with re-defined rules). But I have to export all the variables I need to pass through... which is ugly and adds a bit of a maintenance overhead if those variables change.
... but... it works :)
I will not mark this any time soon, because I am hopeful some genius will point out a neater/better way to do this...

Related

Why is this makefile not building the dependencies, but only when using variables

I have a makefile to generate some headers and cpp files from a yaml file.
../api/%.h ../api/%.cpp : ../idl/%.yml
$(info Generating api files from $<)
$(IDL_TO_CPP_EXE) --input $< --output $(basename $#)
IDL_HEADERS=$(IDL_INPUTS:../idl/%.yml=../api/%.h)
IDL_CPPS=$(IDL_INPUTS:../idl/%.yml=../api/%.cpp)
all: $(IDL_HEADERS) $(IDL_CPPS)
$(info The dependencies are $(IDL_HEADERS) $(IDL_CPPS))
IDL_INPUTS +=../idl/common_api/CommonTypes.yml
When I run it, it outputs the following, but without generating the .h and .cpp file. I've checked they aren't there, so it's not a timestamp issue.
The dependencies are ../api/common_api/CommonTypes.h ../api/common_api/CommonTypes.cpp
make: Nothing to be done for 'all'.
If I manually expand the variables to the following, then it suddenly starts to work! The console output from the logging is exactly the same, and I've been careful to avoid things like hidden characters.
all: ../api/common_api/CommonTypes.h ../api/common_api/CommonTypes.cpp
$(info The dependencies are $(IDL_HEADERS) $(IDL_CPPS))
Why is this makefile working with explicit dependencies, but not with variables?
UPDATE:
all: $(IDL_HEADERS) $(IDL_CPPS)
$(info The dependencies are $^)
$(info The dependencies should be $(IDL_HEADERS) $(IDL_CPPS))
outputs:
The dependencies are
The dependencies should be ../api/common_api/CommonTypes.h ../api/common_api/CommonTypes.cpp
make: Nothing to be done for 'all'.
This turned out to be an ordering problem. When the all rule is parsed, I hadn't set the IDL_INPUTS variable.
IDL_INPUTS gets set later, and the the all rule was run after that, showing the new updated values.

How to compile this file succesfully?

I am trying to compile bt from NPB. I am getting the attached errorCompilation Error . I have also attached the make file I am using.
What am I doing wrong in this case?
MakeFile:
SHELL=/bin/sh
BENCHMARK=bt
BENCHMARKU=BT
include ../config/make.def
OBJS = bt.o \
${COMMON}/c_print_results.o ${COMMON}/c_timers.o ${COMMON}/c_wtime.o
include ../sys/make.common
# npbparams.h is included by header.h
# The following rule should do the trick but many make programs (not gmake)
# will do the wrong thing and rebuild the world every time (because the
# mod time on header.h is not changed. One solution would be to
# touch header.h but this might cause confusion if someone has
# accidentally deleted it. Instead, make the dependency on npbparams.h
# explicit in all the lines below (even though dependence is indirect).
# header.h: npbparams.h
${PROGRAM}: config ${OBJS}
${CLINK} ${CLINKFLAGS} -o ${PROGRAM} ${OBJS} ${C_LIB}
.c.o:
${CCOMPILE} $<
bt.o: bt.c header.h npbparams.h
clean:
- rm -f *.o *~ mputil*
- rm -f npbparams.h core
Seems missing ../sys/setparams
Which should be an executable file, and takes bt A as input arguments.
It might be a depended tool should be built at first. I've tried a search on github, and could find some projects containing, ../sys/setparams.c, maybe, these are what you need.
Hope it helps you.

compile concurrently, link serially

I have big cmake/c++/linux project: a lot of small static libraries, a few big and interdependent static libraries, a few big executable binaries. Single binary with debug symbols is several GB. There are ~10 such binaries (worker, testA, testB, testC...). Compilation usually takes more time than we would like, but we have fast build server and we use make -j20. The worst though is linking. Single linking takes about 60 seconds and 4GB RAM. But when all final binaries are linked at the same time (happens often when 1 small sublibrary was modified, little to recompile, a lot to relink), 10 linkers use 40GB RAM (for 1 developer, there may be more) and very long time. IO is most likely the bottleneck.
We have many developers on 1 strong server and everybody uses make -j20 -l30 so that we don't overload CPU. But we don't have method for limiting number of concurrent linkers. It would be great to limit number of working linkers globally on server, but per make invocation would help as well. Ideally make -j20 -l30 --concurrent-linkers=2. Is it possible?
We use gold linker. We are in progress of separating smaller, independent modules, but this will take a long time.
You could try something like:
$ cat Makefile
OBJS := foo bar baz...
EXES := qux quux quuz...
.PHONY: all
all: $(OBJS)
$(MAKE) -j $(concurrent-linkers) $(EXES)
$(OBJS): ...
<compile>
$(EXES): ...
<link>
And call it with:
$ make -j20 -l30 concurrent-linkers=2
Basically, it separates the build in two make invocations, one for compilation and one for link, with different -j options. The main drawback is that all compilations must be finished before the first link starts. A better solution would be to design a simple link job server (a simple shell script with a bit of flock and tag files would make it) and delegate it the link jobs. But if you can live with this...
Demo with a dummy Makefile:
$ cat Makefile
OBJS := a b c d e f
EXES := u v w x y z
.PHONY: all
all: $(OBJS)
$(MAKE) -j $(concurrent-linkers) $(EXES)
$(OBJS) $(EXES):
#printf 'building $#...\n' && sleep 2 && printf 'done\n' && touch $#
$ make -j20 -l30 concurrent-linkers=2
building a...
building d...
building b...
building c...
building e...
building f...
done
done
done
done
done
done
make -j 2 u v w x y z
make[1]: warning: -jN forced in submake: disabling jobserver mode.
make[1]: Entering directory 'foobar'
building u...
building v...
done
done
building w...
building x...
done
done
building y...
building z...
done
done
make[1]: Leaving directory 'foobar'
As you can see all $(OBJS) targets are built in parallel while the $(EXES) targets are built 2 (maximum) at a time.
EDIT If your makefile is generated by CMake there are at least two options:
Tune your CMake files such that CMake generates two different makefiles: one for compilation and one for link. Then write a simple wrapper makefile like:
.PHONY: myAll myCompile
myAll: myCompile
$(MAKE) -j $(concurrent-linkers) -f Makefile.link
myCompile:
$(MAKE) -f Makefile.compilation
Convince CMake (if it is not already the case) to generate a makefile that defines two make variables: one (OBJS) set to the list of all object files and one (EXES) set to the list of all executable. Then write a simple wrapper makefile like:
.DEFAULT_GOAL := myAll
include CMake.generated.Makefile
.PHONY: myAll
myAll: $(OBJS)
$(MAKE) -j $(concurrent-linkers) $(EXES)
A very similar solution exists if, instead, CMake generates two phony targets, one for all object files and the other for all executable:
.DEFAULT_GOAL := myAll
include CMake.generated.Makefile
.PHONY: myAll
myAll: cmake-target-for-compilation
$(MAKE) -j $(concurrent-linkers) cmake-target-for-link

GNU Make Exits Due to Syntax Error in If Statement

I'm building a C++ project using GNU Make (version 3.80). The makefile is auto-generated from the tool I'm using (IBM Rational Rhapsody). An example of this makefile is at the end of this post.
This makefile has a mechanism that allows me to specify a directory for object files (the OBJ_DIR variable). If this is set, the variable CREATE_OBJ_DIR is set up with the command if not exist $(OBJ_DIR) mkdir $(OBJ_DIR). This is then called for each object file in the project.
Running this makefile without setting an object file directory works as expected; the code is compiled without issues. But running it with OBJ_DIR set to 'build' causes the following error:
C:\Users\XXX\AppData\Local\Temp\make52963.sh: C:\Users\XXX\AppData\Local\Temp\make52963.sh: line 2: syntax error: unexpected end of file
C:\Tools\XXX\x86-win32\bin\make.exe: *** [build/Example.o] Error 2
I'm certain the issue is within the rule for '/build/Example.o', when $(CREATE_OBJ_DIR) is called. If I manually edit the rule and replace $(CREATE_OBJ_DIR) with mkdir $(OBJ_DIR), the command is executed correctly. If I then replace it with if not exist build mkdir build directly, to eliminate any issues due to variable expansion, the same error appears.
Other things I have tried:
Run a cmd shell with the same environment variables set as when the makefile is called, and attempted to run the if not exist build mkdir build command. No issues with this.
Ensure that no trailing characters are present in the command run within the makefile. None appear to be present.
My only conclusion at this point is that something about if statements causes the makefile to fail, but I'm not sure what. Is there anything else I should try to track down the source of this problem? Am I missing something obvious.
Let me know if more details are required.
Note: I've edited this makefile pretty heavily, so it's just to give an idea of what I'm using, and probably won't execute. Some of the environment variables below are set up in a batch file prior to calling make, but I'm confident they're not part of the issue I'm seeing, as the makefile works correctly except in the situation described above.
CPU = XXX
TOOL = gnu
INCLUDE_QUALIFIER=-I
LIB_CMD=$(AR)
LINK_CMD=$(LD)
CPP_EXT=.cpp
H_EXT=.h
OBJ_EXT=.o
EXE_EXT=.out
LIB_EXT=.a
TARGET_NAME=Example
all : $(TARGET_NAME)$(EXE_EXT) Example.mak
TARGET_MAIN=Example
LIBS=
INCLUDE_PATH=
ADDITIONAL_OBJS=
OBJS= \
build/Example.o \
OBJ_DIR=build
ifeq ($(OBJ_DIR),)
CREATE_OBJ_DIR=
else
CREATE_OBJ_DIR= if not exist $(OBJ_DIR) mkdir $(OBJ_DIR)
endif
build/Example.o : src/Example.cpp
#echo Compiling src/Example.cpp
$(CREATE_OBJ_DIR)
#$(CXX) $(C++FLAGS) -o build/Example.o src/Example.cpp
You are thinking to complex. A far simpler solution here is to use:
mkdir -p $(OBJ_DIR)
This will also make it work if OBJ_DIR=my/little/obj/dir/deep/down/the/rabit/hole.
Look at the following Makefile:
OBJ_DIR=foo
CREATE_OBJ_DIR= if not exist $(OBJ_DIR) mkdir $(OBJ_DIR)
$(info CREATE_OBJ_DIR=$(CREATE_OBJ_DIR))
all:
$(CREATE_OBJ_DIR)
and it's output:
% make
CREATE_OBJ_DIR=if not exist foo mkdir foo
if not exist foo mkdir foo
/bin/sh: 1: Syntax error: end of file unexpected (expecting "then")
Makefile:8: recipe for target 'all' failed
make: *** [all] Error 2
Your "if" statement is simply not valid shell syntax. On the other hand if OBJ_DIR is empty then CREATE_OBJ_DIR is empty and that is valid.

How to use makedepend in a non-standard makefile name

I am trying to use makedepend in a makefile named Makefile_abc.
Normally when I have to build a target trg, I say
make -f Makefile_abc trg
and this works beautifully.
I have added following lines in this makefile.
dep:
makedepend main.c
Now, when I do,
make -f Makefile_abc dep
I get the error,
makedepend: error: [mM]akefile is not present
make: *** [depend] Error 1
If I rename my makefile as Makefile, then following command works fine,
make depend
So, I am looking for a way to use makedepend on non-standard makefile names.
This is a basic 'read the manual' question.
Looking at makedepend(1), you need -fMakefile_abc in the recipe for the target dep (optionally with a space between -f and Makefile_abc):
dep:
makedepend -fMakefile_abc main.c
To update the dependencies, you'd run:
$ make -f Makefile_abc dep
This would cause make to run:
makedepend -fMakefile_abc main.c
(Note that the 'standard' — most common — name for the target is depend rather than dep, so you'd normally run make -fMakefile_abc depend or, with a plain makefile file, make depend.)
If you're using GNU Make, you might also add another line to Makefile_abc:
.PHONY: dep # Or depend, depending…
This tells make that there won't be a file dep created by the rule.
You can often get information about how to run a command by using makedepend --help or makedepend -: — the first may (or may not) give a useful help message outlining options, and the second is very unlikely to be a valid option which should generate a 'usage' message that summarizes the options.