c++cmakecmake-language

cmake library - relative path fails but absolute path succeeds


I have a cmakefile that's very basic.
This is the relevant portion:

# The object files of ds
set(DS_LIB_FOLDER ../../build/)
set(DS_LIB ds)
get_filename_component(DS_LIB_FOLDER_ABS "${CMAKE_CURRENT_SOURCE_DIR}/${DS_LIB_FOLDER}" ABSOLUTE)
set(DS_LIB_PATH ${DS_LIB_FOLDER_ABS}/lib${DS_LIB}.a)

When I remove the absolute path and use relative (see the last line) like so:

# The object files of ds
set(DS_LIB_FOLDER ../../build/)
set(DS_LIB ds)
get_filename_component(DS_LIB_FOLDER_ABS "${CMAKE_CURRENT_SOURCE_DIR}/${DS_LIB_FOLDER}" ABSOLUTE)
set(DS_LIB_PATH ${DS_LIB_FOLDER}/lib${DS_LIB}.a)

I get the error:

ninja: error: '../../build/libds.a', needed by 'HostUnitTest', missing and no known rule to make it

It also fails if I use gnu makefiles as the build system.

I made sure the file exists:

user@wsl:/mnt/c/work/project/product/tests/hosts$ ls -l ../../build/libds.a
-rwxrwxrwx 1 user user 333466584 May 25 13:19 ../../build/libds.a
user@wsl:/mnt/c/work/project/product/tests/hosts$ ls -l
total 4
-rwxrwxrwx 1 user user 1471 May 25 14:13 CMakeLists.txt
drwxrwxrwx 1 user user 4096 May 25 14:13 build
-rwxrwxrwx 1 user user  272 May 25 11:54 main.cpp
drwxrwxrwx 1 user user 4096 May 24 10:50 unit_tests

QUESTION
Why does it fail? In both cases, the relative path is used.
In the absolute case, the relative path is used implicitly in the derivation of the absolute path.


Solution

  • Use relative paths to ${CMAKE_CURRENT_SOURCE_DIR}, the path where the currently being processed CMakeLists.txt is located. I.e. replace

    set(DS_LIB_FOLDER ../../build/)
    

    with

    set(DS_LIB_FOLDER "${CMAKE_CURRENT_SOURCE_DIR}/../../build/")