Positioning GCC attributes in declarations

Viewed 377

Does the GCC compiler care where we put the attribute statements inside of declarations? For example is the following equivalent:

void foobar (void) __attribute__ ((section ("bar")));

__attribute__ ((section ("bar"))) void foobar (void);

I have seen here that there is no convention on how they are used. Sometimes before declaration, sometimes after.

2 Answers

The example shared by you (with respect to function attributes) is equivalent. However, only the usage of attributes in this example is equivalent. It may not be generalized.

For instance, the GCC documentation here: 6.39 Attribute Syntax

An attribute specifier list may appear immediately before a declarator (other than the first) in a comma-separated list of declarators in a declaration of more than one identifier using a single list of specifiers and qualifiers. Such attribute specifiers apply only to the identifier before whose declarator they appear. For example, in

__attribute__((noreturn)) void d0 (void),
    __attribute__((format(printf, 1, 2))) d1 (const char *, ...),
     d2 (void);

the noreturn attribute applies to all the functions declared; the format attribute only applies to d1.

Therefore, it's important to pay attention to the placement of commas and semi-colons as it can extend the application of attributes to more than one function declaration following the attribute.

It depends on what type of declarator shall be subject to the attribute.

An excerpt from https://gcc.gnu.org/onlinedocs/gcc/Attribute-Syntax.html#Attribute-Syntax

Label Attributes

In GNU C, an attribute specifier list may appear after the colon following a label, other than a case or default label. GNU C++ only permits attributes on labels if the attribute specifier is immediately followed by a semicolon (i.e., the label applies to an empty statement). If the semicolon is missing, C++ label attributes are ambiguous, as it is permissible for a declaration, which could begin with an attribute list, to be labelled in C++. Declarations cannot be labelled in C90 or C99, so the ambiguity does not arise there.

Enumerator Attributes

In GNU C, an attribute specifier list may appear as part of an enumerator. The attribute goes after the enumeration constant, before =, if present. The optional attribute in the enumerator appertains to the enumeration constant. It is not possible to place the attribute after the constant expression, if present.

Statement Attributes

In GNU C, an attribute specifier list may appear as part of a null statement. The attribute goes before the semicolon.

...

Related