MuertoExcobito
MuertoExcobito

Reputation: 10039

cmake file(RELATIVE_PATH ...) for files that cannot be relative

Under Windows, it's possible to have directories that cannot be formed relative to one another, because they exist on different drives. Making a minimal CMake script, that attempts this:

cmake_minimum_required(VERSION 3.6)
set(FILEA "C:/Directory/MyFile")
set(FILEB "E:/AnotherDirectory/AnotherFile")
file(RELATIVE_PATH relativePath ${FILEA} ${FILEB})
message("relativePath = ${relativePath}")

Produces (running cmake .):

...
relativePath = E:/AnotherDirectory/AnotherFile
...

This is obviously not correct. Is there any way to determine that the call to file(RELATIVE_PATH ...) has "failed"?

Upvotes: 1

Views: 2494

Answers (1)

Florian
Florian

Reputation: 42842

I've just looked at CMake's source code - in this case SystemTools::RelativePath() - and it just returns the "remote" path by design if the drive letters on Windows are not the same:

// If there is nothing in common at all then just return the full
// path.  This is the case only on windows when the paths have
// different drive letters.  On unix two full paths always at least
// have the root "/" in common so we will return a relative path
// that passes through the root directory.
if (sameCount == 0) {
  return remote;
}

Since in your case there is no error thrown, you can just do something like compare the input with the result and throw the error yourself:

if (NOT FILEA STREQUAL FILEB AND FILEB STREQUAL relativePath)
    message(FATAL_ERROR "... your text goes here ...")
endif()

Upvotes: 3

Related Questions