Gcc attributes with C ++ methods

In GCC with the C ++ method defined in the header file, can attribute syntax be used? Can someone set an example for me, please. The following code does not work:

class foo { public: void my_func() __attribute__((hot)); void my_func() { // Some stuff } }; 

It seems that you should put the attributes in the declaration, not in the function definition. When you define a method / function in the header file, you do not have a separate declaration.

Also how to use this with templates. For example, the following code cannot compile with an error: attributes are not allowed to define a function.

 /// Template version of max for type T template <typename T> inline T max(const T x, const T y) __attribute((const)) { if (x > y) return x; else return y; } 
+7
c ++ gcc powerpc
source share
3 answers

It looks like you might need to move the attribute to the function name. In GCC 4.6.3, your code does not compile, but the code compiles below.

 template <typename T> inline T __attribute__((const)) max(const T x, const T y) { if (x > y) return x; else return y; } 
+6
source share

The following works (g ++ 4.6.3):

 class foo { public: void my_func() __attribute__((hot)) { // Some stuff } }; 
  • You must not use a separate ad
  • You need to remove the back underscores as indicated by @Joachim

Example:

 class foo { public: void my_func() __attribute__((deprecated)) { } void my_func2() __attribute__((noinline)) { } }; int main() { foo f; f.my_func(); f.my_func2(); return 0; } 
 $ g++ -c -Wall -pedantic a.cpp a.cpp: In function int main(): a.cpp:12:13: warning: void foo::my_func() is deprecated (declared at a.cpp:3) [-Wdeprecated-declarations] 
+1
source share

I believe that putting an attribute after the <> template and before all decorators in the function definition work best. This compiles with gcc and arm clang along with MacOS clang. And I no longer need separate declarations. It was also my only option with a templated template function using arm gcc.

This worked inside and outside the class with and without templates.

 class foo { public: __attribute__((pure)) void my_func() { // Some stuff } template <typename T> __attribute__((pure)) void my_func(T t) { // Some stuff } }; template <typename T> __attribute((const)) inline T max(const T x, const T y) { if (x > y) return x; else return y; } 
0
source share

All Articles