使用C++方法的gcc属性

Sha*_*ook 10 c++ gcc powerpc

在GCC中使用头文件中定义的C++方法,是否可以使用属性语法?请有人为我提供一个例子.以下代码不起作用:

class foo
{
    public:
        void my_func() __attribute__((hot));
        void my_func()
        {
            // Some stuff
        }
};
Run Code Online (Sandbox Code Playgroud)

看起来你必须把属性放在声明中,而不是放在函数的定义中.在头文件中定义方法/函数时,您没有单独的声明.

另外如何在模板中使用它.例如,以下代码无法使用'错误进行编译:函数定义中不允许使用属性'.

/// 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;
}
Run Code Online (Sandbox Code Playgroud)

Min*_*ine 8

看起来您可能需要将属性移动到函数名称之前.在GCC 4.6.3上,您的代码无法编译,但在代码编译之下.

template <typename T>
inline T __attribute__((const)) max(const T x, const T y)
{
    if (x > y)
        return x;
    else
        return y;
}
Run Code Online (Sandbox Code Playgroud)


And*_*ter 2

以下作品(g++ 4.6.3):

class foo
{
    public:
        void my_func() __attribute__((hot))
        {
            // Some stuff
        }
};
Run Code Online (Sandbox Code Playgroud)
  • 您不得使用单独的声明
  • 您需要删除@Joachim提到的尾随下划线

例子:

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;
}
Run Code Online (Sandbox Code Playgroud)
$ 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]
Run Code Online (Sandbox Code Playgroud)