在适用于 Xcode 的 CMake 中启用 AddressSanitizer 的正确方法是什么

2023-08-27C/C++开发问题
44

本文介绍了在适用于 Xcode 的 CMake 中启用 AddressSanitizer 的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我添加了 AddressSanitizer 标志如下:

I've added AddressSanitizer flag as follow:

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")

使用 Unix Makefiles 时,一切构建和运行良好.

Everything builds and runs fine when using Unix Makefiles.

问题是在生成Xcode项目的时候,它只是不想链接,因为它找不到ASan库.

The problem comes when generating the Xcode project, it just doesn't want to link because it cannot find the ASan library.

我已经找到了两个解决方案,但决定不使用它们,因为它们无法仅使用 CMake 实现自动化:

I already found two solutions, but decided not to use them because they cannot be automated using just CMake:

  1. -Wl,-undefined,dynamic_lookup 添加到链接标志,因此它跳过链接到动态库.
  2. 直接与 libclang_rt.asan_osx_dynamic.dylib 链接.
  1. Adding -Wl,-undefined,dynamic_lookup to the linked flags, so it skips linking to dynamic libraries.
  2. Link with libclang_rt.asan_osx_dynamic.dylib directly.

那么这两种解决方案有什么问题?

So what's the problem with these two solutions?

  • 使用解决方案 #1 时,我必须在 Xcode 中手动打开目标方案并添加指向 libclang_rt.asan_osx_dynamic.dylibDYLD_INSERT_LIBRARIES 环境变量.
  • 使用解决方案 #2 时,ASan 库的路径因计算机而异.

此外,作为另一种解决方案,我尝试从 Xcode 目标方案启用 Address Sanitizer 标志,但有趣的是它没有检测到我添加的问题,所以我没有将其列为解决方案,因为它没有通过我的测试.

Additionally as another solution, I tried enabling Address Sanitizer flag from the Xcode target scheme but interestingly it didn't detect the issues I added, so I didn't list this as a solution because it failed my test.

任何帮助将不胜感激.

推荐答案

您也需要向链接器提供标志.我是这样做的:

You need to provide the flag(s) to the linker too. I'm doing it like this:

set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")
set (CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")

这篇关于在适用于 Xcode 的 CMake 中启用 AddressSanitizer 的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6