# LD\_LIBRARY\_PATH for ExternalProject

**URL:** <https://discourse.cmake.org/t/ld-library-path-for-externalproject/7606>\
**Category:** Code\
**Created:** [March 4, 2023, 1:06pm UTC](https://discourse.cmake.org/t/ld-library-path-for-externalproject/7606 "2023-03-04T13:06:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![magras](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/m/f475e1/32.png) [@magras](https://discourse.cmake.org/u/magras)\
**Post date:** [March 4, 2023, 1:06pm UTC](https://discourse.cmake.org/t/ld-library-path-for-externalproject/7606/1 "2023-03-04T13:06:34Z")

</div>

I’m porting a plugin for llvm compiler to cmake. Functional tests obviously require different toolchain, so I extracted tests into a separate project. With some hacks it almost works. The problem is the toolchain adds a new runtime dependency to every built binary. So to run tests I need to set `LD_LIBRARY_PATH`. Setting it with `set(ENV{LD_LIBRARY_PATH} ...)` doesn’t work.

How can I solve this problem?

I’d prefer to not modify the tests project to be able to build tests with a system compiler for sanity check.

There is simplified code:

```auto
project(compiler_plugin CXX)
add_library(plugin MODULE)
add_library(runtime MODULE)

# Generate toolchain.cmake used for tests project
file(GENERATE
  OUTPUT toolchain.cmake
  CONTENT [[
set(CMAKE_C_COMPILER @CMAKE_SOURCE_DIR@/run_clang_with_plugin.py)
set(CMAKE_C_COMPILER_LAUNCHER env LD_LIBRARY_PATH=$<TARGET_FILE_DIR:plugin>)
set(ENV{LD_LIBRARY_PATH} $<TARGET_FILE_DIR:runtime>) # runtime module should be accessible during execution of tests
]])

# Add tests project
include(ExternalProject)
ExternalProject_Add(
  tests
  SOURCE_DIR ${CMAKE_SOURCE_DIR}/tests
  CMAKE_ARGS
    -DCMAKE_TOOLCHAIN_FILE=${CMAKE_CURRENT_BINARY_DIR}/toolchain.cmake
)

# Hack to be able to run external project tests from main project
# https://discourse.cmake.org/t/testing-in-a-superbuild/1906
ExternalProject_Get_Property(tests BINARY_DIR)
file(RELATIVE_PATH ctest_dir "${CMAKE_CURRENT_BINARY_DIR}" "${BINARY_DIR}")
file(CONFIGURE
  OUTPUT "CTestTestfile.cmake"
  CONTENT [[subdirs("${ctest_dir}")]]
)

```

A minimal example demonstrating that setting environment variable doesn’t work for tests:

```auto
cmake_minimum_required(VERSION 3.25)
project(foo NONE)

set(ENV{FOO} bar)

enable_testing()
add_test(foo env)

```

```bash
cmake -B build
ctest --test-dir build --verbose | grep bar

```

---

<div class="post-metadata">

**Author:** ![magras](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/m/f475e1/32.png) [@magras](https://discourse.cmake.org/u/magras)\
**Post date:** [March 7, 2023, 7:25pm UTC](https://discourse.cmake.org/t/ld-library-path-for-externalproject/7606/2 "2023-03-07T19:25:20Z")

</div>

Kind of solved it with another hack.  
Idea is to move `set(ENV{LD_LIBRARY_PATH} ...)` to generated `CTestTestfile.cmake`.
