如何在gcc中声明和定义纯函数

How to declare and define a pure function in gcc?

本文关键字:定义 函数 声明 gcc      更新时间:2023-10-16

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

但是constpure属性只有在应用于外部声明时才非常有用,所以这应该不是问题。如果定义是可见的,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开始,编译器未知的所有属性都将被忽略,而不会导致错误。因此,上面的代码可以在不同的编译器和平台之间进行移植。