Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using gcc attributes with C++11 attributes syntax

I was trying to use the GCC attributes with the C++11 syntax. For example something like this:

static void [[used]] foo(void)
{
    // ...
}

But I get the following:

warning: ‘used’ attribute ignored [-Wattributes]
static void [[used]] foo(void)
            ^

Why is the attribute ignored? Is it possible to use GCC attributes as C++ attributes?

like image 891
Andres Tiraboschi Avatar asked Apr 22 '15 19:04

Andres Tiraboschi


2 Answers

[[gnu::used]] static void foo(void) {}

First, the attribute can only appear in specific places, otherwise you get:

x.cc:1:13: warning: attribute ignored [-Wattributes]
 static void [[gnu::used]] foo(void) {}
             ^
x.cc:1:13: note: an attribute that appertains to a type-specifier is ignored

Second, used is not a standard warning, so it gets hidden in a proprietary namespace gnu::.

like image 108
Marc Glisse Avatar answered Nov 15 '22 22:11

Marc Glisse


There is no [[used]] attribute in C++ 11, that's why it's being ignored. (*)

There is gcc-specific __attribute__((used)), that can be applied to static object or function definitions. It tells compiler to emit definitions, even if that symbol seems to be unused at all - in other words, it makes you sure, that such symbol will be present in result object file.


(*) It needs to be ignored, because standard allows implementations to define additional, implementation-specific attributes. So there is no point in treating unknown attributes as an error (similar case: #pragma directives).


Some additional info:

Attributes provide the unified standard syntax for implementation-defined language extensions, such as the GNU and IBM language extensions __attribute__((...)), Microsoft extension __declspec(), etc.

And, probably the most important part:

Only the following attributes are defined by the C++ standard. All other attributes are implementation-specific.

  • [[noreturn]]
  • [[carries_dependency]]
  • [[deprecated]] (C++14)
  • [[deprecated("reason")]] (C++14)

Source: attribute specifier sequence.

like image 44
Mateusz Grzejek Avatar answered Nov 15 '22 22:11

Mateusz Grzejek