ISO C 标准中 __attribute__ 的替换是什么?

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

ISO C 标准中

__attribute__
的替代是什么? 我想移植我的独立于编译器的软件。

c attributes iso
3个回答
4
投票

没有一个。

一种解决方案是抽象宏背后的属性。例如:

#ifdef __GNUC__
#define UNUSED __attribute((unused))__
#else
#define UNUSED
#endif

...

void function(void) UNUSED;

0
投票

此 gcc 扩展提供的各种设施没有通用替代品。大多数不与 gcc 兼容的其他编译器使用

#pragma
来实现类似的目标。从 C99 开始,C 有了
_Pragma
运算符,它允许您在代码中间(不仅在正确的行上)喷出编译指示,并使用宏组成编译指示的内容。但是,您仍然需要对各个功能进行特定的“翻译”以适应目标编译器的相应编译指示语法。


0
投票

C23 引入了属性说明符序列,即这些属性:

[[deprecated]]
[[deprecated("reason")]]
[[fallthrough]]
[[nodiscard]]
[[nodiscard("reason")]]
[[maybe_unused]]
[[noreturn]]
[[_Noreturn]]
[[unsequenced]]
[[reproducible]]

您可以使用宏

__has_c_attribute
来检测这些属性的可用性:

#if defined(__has_c_attribute)
    /* They are available. Further do: */
    #if __has_c_attribute(deprecated)
    /* to check for the availability of individual attributes. */

为了巩固 ISO C 和 GNU C 的属性,我经常这样做:

#if defined(__has_c_attribute)
    #if __has_c_attribute(fallthrough)
        #define ATTRIB_FALLTHROUGH        [[fallthrough]]
    #endif
#elif defined(__GNUC__) || defined(__clang__) || defined(__INTEL_LLVM_COMPILER)
    #define ATTRIB_FALLTHROUGH            __attribute__((fallthrough))
#else 
    #define ATTRIB_FALLTHROUGH            /**/
#endif 

#if !defined(ATTRIB_FALLTHROUGH)
    #define ATTRIB_FALLTHROUGH            /**/
#endif

如果编译器尚不支持 ISO C 的属性,但支持 GNU C 的属性,则宏将扩展以利用 GNU C 的

fallthrough
属性。否则,它就会膨胀成无。

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