Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a makefile, how to get the relative path from one absolute path to another?

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?

like image 469
x-x Avatar asked Jul 27 '10 07:07

x-x


People also ask

How do you convert an absolute path to a relative path?

The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.

How do I get the current relative directory of my Makefile?

You can use shell function: current_dir = $(shell pwd) . Or shell in combination with notdir , if you need not absolute path: current_dir = $(notdir $(shell pwd)) .

Can an absolute path be a relative path?

A path is either relative or absolute. An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path.

How do you reference a relative path?

Relative path Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy. A single dot represents the current directory itself.


1 Answers

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:

rootdir = $(realpath .)
default:
    @$(MAKE) --directory=$(rootdir)/src/libs/libfoo includedir=../../../include

Then you can use $(includedir) in the sub-makefiles. It is already defined as relative.

like image 166
Didier Trosset Avatar answered Sep 23 '22 01:09

Didier Trosset