Reputation: 31
What is the replacement of __attribute__
in ISO C standard?
I want to port my software which is compiler independent.
Upvotes: 3
Views: 1692
Reputation: 7345
C23 has introduced attribute specifier sequences, namely these attributes:
[[deprecated]]
[[deprecated("reason")]]
[[fallthrough]]
[[nodiscard]]
[[nodiscard("reason")]]
[[maybe_unused]]
[[noreturn]]
[[_Noreturn]]
[[unsequenced]]
[[reproducible]]
You can use the macro __has_c_attribute
to detect the availability of these attributes:
#if defined(__has_c_attribute)
/* They are available. Further do: */
#if __has_c_attribute(deprecated)
/* to check for the availability of individual attributes. */
To consolidate ISO C's and GNU C's attributes, I often do something like this:
#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
In cases where a compiler does not yet support ISO C's attributes but does support GNU C's attributes, the macro will expand to utilize GNU C's fallthrough
attribute. Otherwise, it will expand to nothing.
Upvotes: 0
Reputation: 78923
There is no general replacement for the wide range of facilities that this gcc extension offers. Most other compilers that are not gcc compatible use #pragma
to achieve similar goals. Since C99, C has the _Pragma
operator that allows you to spew pragmas in the middle of your code (not only on proper lines) and to compose the contents of a pragma with macros. But then you still have to do specific "translations" of individual features to the corresponding pragma syntax of your target compiler.
Upvotes: 0
Reputation: 272577
There isn't one.
One solution is to abstract the attributes behind macros. e.g.:
#ifdef __GNUC__
#define UNUSED __attribute((unused))__
#else
#define UNUSED
#endif
...
void function(void) UNUSED;
Upvotes: 4