Gabriel Staples
Gabriel Staples

Reputation: 52489

Is there a difference between `__attribute__((some_attribute))` and `[[some_attribute]]`?

I just came across attributes enclosed in square brackets for the first time, and I've been doing a little background reading: http://en.cppreference.com/w/cpp/language/attributes.

For gcc at least, there seem to be multiple techniques allowed:

__attribute__((some_attribute))

and

[[some_attribute]]

Is this correct? When is one technique allowed or not allowed, preferred or not preferred? What's the difference?

It looks like [[some_attribute]] is allowed as of C++11 only, right?

Upvotes: 5

Views: 935

Answers (2)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

According to N4659:

10.6.1 Attribute syntax and semantics [dcl.attr.grammar]

Attributes specify additional information for various source constructs such as types, variables, names, blocks, or translation units.

attribute-specifier-seq:
    attribute-specifier-seqopt attribute-specifier

attribute-specifier: 
    [ [ attribute-using-prefixopt attribute-list ] ]
    alignment-specifier

So, [[...]] is a standardized syntax.

In opposite, __attribute__ ((attribute-list)) is a syntax of gcc extension:

An attribute specifier is of the form __attribute__ ((attribute-list)). An attribute list is a possibly empty comma-separated sequence of attributes, where each attribute is one of the following:

...

As attributes were introduced in C++11 and you use gcc with C++11 support (or newer), then both types of syntax are available for you.

Upvotes: 2

Jesper Juhl
Jesper Juhl

Reputation: 31457

The [[foo]] syntax was introduced with C++11. But many compilers had their own syntax before that (which in some cases also supports some non-standardized attributes).

So in short: [[foo]] is standard and should work everywhere with a conforming compiler. The other syntaxes are compiler specific.

Upvotes: 2

Related Questions