cannot use CMAKE_SOURCE_DIR in toolchain file

When trying to include something from CMAKE_SOURCE_DIR in a toolchain-file, cmake seems to make a flat copy of the file for compiler-tests, then /CMakeFiles/CMakeTmp/CMakeLists.txt:3 cannot find the include-file in /CMakeFiles/CMakeTmp/

Example: we are using conan and our compiler is provided as a conan-package. Conan will generate a conanbuildinfo.cmake which will provide path-variables for all tools. toolchain-file:

```
include(${CMAKE_SOURCE_DIR}/conanbuildinfo.cmake)
set(CMAKE_C_COMPILER ${CONAN_BIN_DIRS_CLANG}/clang-cl.exe)
set(CMAKE_CXX_COMPILER ${CONAN_BIN_DIRS_CLANG}/clang-cl.exe)
set(CMAKE_LINKER ${CONAN_BIN_DIRS_CLANG}/lld-link.exe)
```

output:

```
-- The C compiler identification is Clang 9.0.0 with MSVC-like command-line
-- The CXX compiler identification is Clang 9.0.0 with MSVC-like command-line
-- Check for working C compiler: user/.conan/data/clang/9.0.0/tools/stable/package/9d74748ca8155c54bee5ded2267de5f3e409cf81/bin/clang-cl.exe
CMake Error at C:/src/Example/tool-clang-windows-x86.cmake:8 (include):
  include could not find load file:

    C:/src/Example/CMakeFiles/CMakeTmp/conanbuildinfo.cmake
Call Stack (most recent call first):
  C:/src/Example/CMakeFiles/3.15.4/CMakeSystem.cmake:6 (include)
  C:/src/Example/CMakeFiles/CMakeTmp/CMakeLists.txt:3 (project)
```

The toolchain file is C:/src/Example/tool-clang-windows-x86.cmake, but where is conanbuildinfo.cmake exactly? If it is a sibling of the toolchain file, then I would use

include("${CMAKE_CURRENT_LIST_DIR}/conanbuildinfo.cmake")

Sorry for reviving an old topic, but I think it makes sense.

I have the same issue, only in my case the included file is not a sibling but a few directories above - meaning I can’t use CMAKE_CURRENT_LIST_DIR as starting point. I’d really want to specify it from CMAKE_SOURCE_DIR instead.
Is this possible? If not, why not?

Edit: I can do something like ${CMAKE_CURRENT_LIST_DIR}../../../myfile.cmake so I guess the question “why” I can’t base this off off CMAKE_SOURCE_DIR still stands?

Toolchain files are used not just for the main project, but also for try_compile() calls which create their own separate mini-projects to implement the compile test. For these separate mini-projects, the CMAKE_SOURCE_DIR would be a different directory to the value reported by the main project’s CMAKE_SOURCE_DIR. You should consider the only reliable variables to be those that are relative to the location of the toolchain file itself (e.g. CMAKE_CURRENT_LIST_DIR).

1 Like