An example to illustrate my question:
Top level makefile
rootdir = $(realpath .)
export includedir = $(rootdir)/include
default:
@$(MAKE) --directory=$(rootdir)/src/libs/libfoo
Makefile for src/libfoo
currentdir = $(realpath .)
includedir = $(function or magic to make a relative path
from $(currentdir) to $(includedir),
which in this example would be ../../../include)
Another example:
current dir = /home/username/projects/app/trunk/src/libs/libfoo/
destination = /home/username/projects/app/build/libfoo/
relative = ../../../../build/libfoo
How can this be done, while trying to be as portable as possible?
Python is portable! So, I would suggest you this simple example in your submakefile
With
current_dir
anddestination_dir
pathsos.path.relpath()
does the job for you so you do not have to re-invent the wheel.submakefile.mk
The shell has this feature using realpath(1) and the --relative-to flag so you could just invoke the shell.
Here is an example:
You can even process a whole list of files with one invocation of realpath(1) since it knows how to process many file names.
Here is an example:
Didier's answer is the best one, but the following might give you some ideas:
Sorted!
(no-one said it had to be pretty...)
Here's a solution that only uses GNU make functions. Even though it's recursive, it ought to be more efficient than calling an external program. The idea is pretty straight forward: the relative path will be zero or more .. to go up to the most common ancestor, then a suffix to go down to the 2nd directory. The hard part is finding the longest common prefix in both paths.
I recently translated a large set of recursive makefiles into a whole project make as it's well known that recursive make is bad due to not exposing the entire dependence graph (http://aegis.sourceforge.net/auug97.pdf). All source code and library paths are defined relative to the current makefile directory. Instead of defining a fixed number of generic % build rules, I create a set of rules for every (source code directory, output directory) pair, which avoids the ambiguity of using vpath. When creating the build rules, I need a canonical path for each source code directory. Although the absolute path can be used, it's usually too long and less portable (I happened to be using Cygwin GNU make where absolute paths have a /cygdrive prefix and aren't recognized by Windows programs). Therefore, I use this function heavily for generating canonical paths.
Robust drop-in solution with pure Make:
Test cases:
Expected results:
Doing what you want does not look easy. It may be possible using a lot of combined
$(if
in the makefile but not portable (gmake only) and cumbersome.IMHO, you are trying to solve a problem that you create yourself. Why don't you send the correct value of
includedir
as a relative path from the Top-level Makefile? It can be done very easily as follows:Then you can use
$(includedir)
in the sub-makefiles. It is already defined as relative.