LD_LIBRARY_PATH for ExternalProject

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:

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:

cmake_minimum_required(VERSION 3.25)
project(foo NONE)

set(ENV{FOO} bar)

enable_testing()
add_test(foo env)
cmake -B build
ctest --test-dir build --verbose | grep bar

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