如何在gcc中声明和定义纯函数
How to declare and define a pure function in gcc?
GCC具有pure和const属性,其中const实际上用于实纯函数(pure用于无副作用的幂等函数)。
那么,如何使用const属性声明和定义函数呢?
编辑:我感兴趣的是真正的纯函数,用const属性声明的函数,而不是用纯属性声明的。
示例:
// Declaration:
int square (int x) __attribute__ ((const));
// Definition:
int __attribute__ ((const)) square (int x)
{
return x*x;
}
所有属性的语法基本相同:__attribute__ (( <attribute-name> ))
或__attribute__ (( <attribute-name> ( <attribute-options> ) ))
。引用您链接到的文档:
关键字
__attribute__
允许您在进行声明时指定特殊属性。该关键字后面是一个位于双括号内的属性规范。
您链接到的文档中有几个其他属性的示例,包括pure
:
int square (int) __attribute__ ((pure));
因此,从语法角度来看,使用const
只需要将pure
更改为const
:
int square (int) __attribute__ ((const));
正如评论中所指出的:如果你在定义中使用它,那么你需要把__attribute__ ((const))
放在不同的位置:
int square (int) __attribute__ ((const)) { ... } // doesn't work
int __attribute__ ((const)) square (int) { ... } // does work
但是const
和pure
属性只有在应用于外部声明时才非常有用,所以这应该不是问题。如果定义是可见的,GCC通常能够在没有您帮助的情况下确定函数是否可以被视为const
/pure
。
根据本文,语法与@hvd所说的匹配:
int square (int) __attribute__ ((pure));
然而,在编译以下示例时,gcc
似乎没有强制执行不检查全局状态的属性。
#include <stdio.h>
int square (int) __attribute__ ((pure));
int outerX = 7;
int square(int x) {
return outerX * x;
}
int main(){
printf("%dn", square(5));
return 0;
}
下面没有打印任何错误,代码运行并生成35
。
gcc -Wall -Werror -pedantic -O3 Pure.c
gcc --version
gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
更奇怪的是,gcc
也不在乎我们是否会改变函数内部的全局状态,并在每次调用时返回不同的值,因为它会导致全局状态的变化。
#include <stdio.h>
int square (int) __attribute__ ((pure));
int outerX = 7;
int square(int x) {
outerX++;
return outerX * x;
}
int main(){
printf("%dn", square(5));
printf("%dn", square(5));
printf("%dn", square(5));
return 0;
}
输出:
40
45
50
从C++11开始,可以使用属性说明符序列来指定此类属性。例如:
[[ gnu::const ]]
int square (int x)
{
return x * x;
}
此外,从C++17开始,编译器未知的所有属性都将被忽略,而不会导致错误。因此,上面的代码可以在不同的编译器和平台之间进行移植。
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数