如何在 CMake 中设置 ASAN_OPTIONS 环境变量?

How to set ASAN_OPTIONS environment variable in CMake?

据我了解,要在clang中使用ASAN_OPTIONS,必须在编译前设置ASAN_OPTIONS环境变量。

如何在不添加包装器脚本的情况下在 CMake 脚本中执行此操作?

仅当使用 clang 编译时,我才需要为一个特定的测试项目禁用 ODR 违规检查。所以在 CMakeLists.txt 文件中我有:

if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
  # Clange reports ODR Violation errors in mbedtls/library/certs.c.  Need to disable this check.
  set(ENV{ASAN_OPTIONS} detect_odr_violation=0)
endif()

但是在运行cmake之后,如果我输入echo $ASAN_OPTIONS,则没有设置。

在运行cmake之后,如果我输入:

export ASAN_OPTIONS=detect_odr_violation=0
make

一切都很好。

cmake 是否可以设置环境变量使其在 cmake 运行后仍然存在?抱歉我对环境的了解有限!

Is it possible for cmake to set an environment variable so it persists after cmake runs?

不行这个不行。您不能在 CMake 的父进程中设置环境变量。 set 命令的文档甚至警告您这一点。

来自here

This command affects only the current CMake process, not the process from which CMake was called, nor the system environment at large, nor the environment of subsequent build or test processes.


但是,您可以通过 CMAKE_CXX_COMPILER_LAUNCHER 变量解决这个特定问题:

set(CMAKE_CXX_COMPILER_LAUNCHER ${CMAKE_COMMAND} -E env ASAN_OPTIONS=detect_odr_violation=0 ${CMAKE_CXX_COMPILER_LAUNCHER})

这将调用带有相关环境变量集的编译器。请参阅此处的文档:https://cmake.org/cmake/help/latest/prop_tgt/LANG_COMPILER_LAUNCHER.html

As far as I understand, to use ASAN_OPTIONS with clang, the ASAN_OPTIONS environment variable must be set before compiling.

不完全是,ASAN_OPTIONS 不会以任何方式影响编译。相反,它控制 编译代码 的行为,因此需要在 运行 测试之前设置(并导出)。

在你的情况下,使用不同的控制机制会更容易:__asan_default_options callback:

#ifndef __has_feature
// GCC does not have __has_feature...
#define __has_feature(feature) 0
#endif

#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
#ifdef __cplusplus
extern "C"
#endif
const char *__asan_default_options() {
  // Clang reports ODR Violation errors in mbedtls/library/certs.c.
  // NEED TO REPORT THIS ISSUE
  return "detect_odr_violation=0";
}
#endif