使用 gcc 4.8 构建时如何检测是否使用地址清理器构建?

问题描述 投票:0回答:3

我正在开发一个用 C 语言编写的程序,我偶尔会使用地址清理程序来构建该程序,主要是为了捕获错误。该程序在启动时会在日志中打印一个横幅,其中包含以下信息:谁构建了它,构建它的分支,编译器等。我想最好也能说明二进制文件是否是使用地址清理程序构建的。我知道有 __has_feature(address_sanitizer),但这只适用于 clang。我尝试了以下简单的程序:

#include <stdio.h>

int main()
{
#if defined(__has_feature)
# if __has_feature(address_sanitizer)
    printf ("We has ASAN!\n");
# else
    printf ("We have has_feature, no ASAN!\n");
# endif
#else
    printf ("We got nothing!\n");
#endif

    return 0;
}

使用

gcc -Wall -g -fsanitize=address -o asan asan.c
构建时,会产生:

We got nothing!

随着

clang -Wall -g -fsanitize=address -o asan asan.c
我得到:

We has ASAN!

是否有与 __has_feature 等效的 gcc?

我知道有一些方法可以检查,比如使用地址清理程序构建的程序的巨大 VSZ 值,只是想知道是否有编译时定义或其他东西。

c gcc clang address-sanitizer
3个回答
31
投票

来自GCC 4.8.0手册

__SANITIZE_ADDRESS__

当使用

-fsanitize=address
时,定义该宏,其值为 1。


3
投票

您还可以选择:

#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)

您可能需要

#include <sanitizer/asan_interface.h>


0
投票

请注意,GCC 没有

__has_feature
并且 clang 没有设置
__SANITIZE_ADDRESS__

所以这应该适用于 clang 和 GCC:

#if defined(__has_feature)
#   if __has_feature(address_sanitizer) // for clang
#       define __SANITIZE_ADDRESS__ // GCC already sets this
#   endif
#endif

#if defined(__SANITIZE_ADDRESS__)
    // ASAN is enabled . . .
#endif
© www.soinside.com 2019 - 2024. All rights reserved.