liveBook · Manning

__has_c_attribute

As explained in Modern C, Third Edition

__has_c_attribute is a C preprocessor feature-test operator that reports whether an attribute is supported.

__has_c_attribute is a C23 preprocessor feature-test operator. Use it in a preprocessor conditional to test whether an attribute is supported before applying that attribute. section 10.2.3

Guarding a format attribute

The conditional applies the GNU format attribute only when the implementation reports support. The attribute tells the compiler that snprintf uses a printf-style format at argument 3 and begins its variable arguments at argument 4, enabling format warnings. section 10.2.3

#if __has_c_attribute(__gnu__::__format__)
  [[__gnu__::__format__(__printf__, 3, 4)]]
#endif
  int snprintf(char *buf, size_t size, const char *frmt, ...);

Inspect a conditional declaration using __has_c_attribute and the double-underscore form of the prefixed format attribute. section 10.2.3

 #ifndef __has_c_attribute
 # define __has_c_attribute(X) 0
 #endif

Inspect a fallback definition that makes an unavailable __has_c_attribute operator evaluate to zero. section 10.2.3

How Modern C, Third Edition covers it

How deep it goes
Defines conditional use and a fallback query, while stopping short of specifying attribute implementation details.
Examples
Demonstrates guarding __gnu__::__format__ and defining __has_c_attribute as zero when the operator is unavailable.
What it assumes
Assumes familiarity with C attributes and preprocessor conditionals, while showing how to test for the operator itself.
What you can do after
Apply it via preprocessor conditionals to select supported attributes and provide a zero-valued fallback.
How it connects
Connects C23 attributes with preprocessor conditionals, feature testing, macros, and compiler portability.

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.