整合 GNU C 和 C23 已弃用的函数属性

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

我在使用下面的宏时遇到的问题

// Assume that __GNUC__ or __clang__ is defined. 

#if defined(__has_c_attribute)
    #if __has_c_attribute(deprecated)
        #define ATTRIBUTE_DEPRECATED(...)          [[deprecated(__VA_ARGS__)]]
    #endif    /* deprecated */
#else  
    #define ATTRIBUTE_DEPRECATED(...)              __attribute__((deprecated(__VA_ARGS__)))
#endif    /* __has_c_attribute */

__attribute__((deprecated()))
__attribute__((deprecated))
是等价的,但
[[deprecated()]]
[[deprecated]]
不是等价的。

使用以下任一方法调用时,

#else
块可以正常工作:

ATTRIB_DEPRECATED()
ATTRIB_DEPRECATED("privat")

因为GNU C允许属性的参数列表为空。

但是当使用

std=c2x
编译时,
#if
块不会,并且失败:

deprecated.c:12:14: error: parentheses must be omitted if attribute argument list is empty

有没有办法让我也能使用相同的代码来使用 C23?

如果我能写一下就更好了:

ATTRIB_DEPRECATED

而不是:

ATTRIB_DEPRECATED()

如果没有提供任何论据。

对于 MRE:

// Assume that __GNUC__ or __clang__ is defined. 

#if defined(__has_c_attribute) 
    #if __has_c_attribute(deprecated)
        #define ATTRIBUTE_DEPRECATED(...)          [[deprecated(__VA_ARGS__)]]
    #endif
#else  
    #define ATTRIBUTE_DEPRECATED(...)              __attribute__((deprecated(__VA_ARGS__)))
#endif    /* __has_c_attribute */

ATTRIBUTE_DEPRECATED() int min(int a, int b)
{
    return a < b ? a : b;
}

int main() {
    return min(10, 20);
}

上面的代码只会编译 f

__has_c_attribute
未定义。

c gcc clang c-preprocessor c23
1个回答
0
投票

我相信你必须有两个单独的宏

#if defined(__has_c_attribute) 
    #if __has_c_attribute(deprecated)
        #define ATTRIBUTE_DEPRECATED          [[deprecated]]
    #endif
#else  
    #define ATTRIBUTE_DEPRECATED              __attribute__((deprecated))
#endif    /* __has_c_attribute */

#if defined(__has_c_attribute) 
    #if __has_c_attribute(deprecated)
        #define ATTRIBUTE_DEPRECATEDR(...)          [[deprecated(#__VA_ARGS__)]]
    #endif
#else  
    #define ATTRIBUTE_DEPRECATEDR(...)              __attribute__((deprecated))
#endif    /* __has_c_attribute */


ATTRIBUTE_DEPRECATEDR(Reason) int min(int a, int b)
{
    return a < b ? a : b;
}

ATTRIBUTE_DEPRECATED int max(int a, int b)
{
    return a > b ? a : b;
}

int main() {
    return min(max(10,20), max(10, 20));
}

https://godbolt.org/z/c7T13ab3j

© www.soinside.com 2019 - 2024. All rights reserved.