Skip to content

Add function for joining paths

I am trying to join two paths together:

SET(CMAKE_INSTALL_PKGLIBDIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/foo")

but a string concatenation does not really do it when CMAKE_INSTALL_LIBDIR contains an absolute path.

Is there a CMake function that takes multiple path arguments and joins relative paths right of the rightmost absolute path to the absolute path, like Python’s os.path.join does?

Examples from Python interpreter showing desired behavior:

>>> from os.path import join
>>> join("/foo/bar", "/baz/qux")
'/baz/qux'
>>> join("foo/bar", "/baz/qux")
'/baz/qux'
>>> join("/foo/bar", "./baz/qux")
'/foo/bar/./baz/qux'
>>> join("/foo/bar", "../baz/qux")
'/foo/bar/../baz/qux'
>>> join("./foo/bar", "baz/qux")
'./foo/bar/baz/qux'

I need to handle both the cases where the prefix is absolute (e.g. CMAKE_INSTALL_PREFIX), and where it is relative (e.g. $ORIGIN/.. or ${prefix} often needed for pkg-config files). And orthogonally, I need to handle both Linux distributions that use relative CMAKE_INSTALL_LIBDIR, and those that use an absolute one.

When asked about a solution on StackOverflow, it was suggested to me to use if statements but this is clumsy and repetitive. I could refactor it to a function but there are so many projects I need to add this to, I feel like this should be built into CMake.

To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information