GCC Attributes

From MozillaWiki
Jump to: navigation, search

This page presents a few notes on GCC Attribute syntax and usage. I had to create it because I can't find any easy to use docs on the web and I get sick of figuring this out again and again. --dmandelin@mozilla.com

GCC Attributes are used to add various annotations to code outside of the basic source language that assist the compiler. There is also a user attribute that is not interpreted by the compiler but can be used by plugins and static analyses.

The original docs on attributes are at [1].

Attribute Specifier Syntax

Here is an example of a basic attribute specifier:

__attribute__((user("foo")))

In EBNF:

attribute-specifier =
   "__attribute__((", attribute-list, "))"
attribute-list =
   [ attribute, { ",", attribute } ]
attribute = 
   ? empty ? | word | word, "(", attribute-parameters, ")"
attribute-parameters =
   identifier { ",", expression }
 | [ expression, { ",", expression } ]

Attribute Specifier Placement

Classes

Preferred style:

class __attribute__((user("foo"))) C { ... };

Alternate style:

class C { ... } __attribute__((user("foo")));

Functions

Attributes can go almost anywhere:

 __attribute__((user("foo"))) int f();
 int __attribute__((user("foo"))) f();
 int f() __attribute__((user("foo")));

Variables

Again, attributes can be placed freely:

 __attribute__((user("foo"))) int n;
 int __attribute__((user("foo"))) n;
 int n __attribute__((user("foo")));

Function parameters work just like variables.