gcc函数嵌套

新发现gcc的一些扩展,虽然以前也一直知道,但是从来没有用过。今天无意中看到关于函数嵌套的代码,大概是这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>

static void rebuild_from_analysis(void)
{
auto void flush_row(void) {
fprintf(stderr, "%s %s %d\n", __FILE__, __func__, __LINE__);
}
flush_row();
}
int main(int argc, char* argv[]){
rebuild_from_analysis();
fprintf(stderr, "%s %s %d\n", __FILE__, __func__, __LINE__);

return 0;
}

vscodeclang语法检查auto void flush_row(void)红色波浪线提示Function definition is not allowed hereclang(function_definition_not_allowed),并且调用的时候flush_row();也提示Call to undeclared function 'flush_row'; ISO C99 and later do not support implicit function declarationsclang(-Wimplicit-function-declaration)

尝试编译

1
gcc -o test1 test.c -O2 -Wall -Wextra -Wno-unused-parameter -g

发现竟然没有报错,甚至警告也没有

尝试运行

1
2
3
dky@LAPTOP-Q5IILQ3E:~/workspaces$ ./test1 
test.c flush_row 6
test.c main 12

竟然完美运行!

于是我马上看了下我的wslubuntu中的gcc版本,经查是gcc-13,2023年发布

1
2
3
4
5
dky@LAPTOP-Q5IILQ3E:~/workspaces$ gcc --version
gcc (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0
Copyright (C) 2023 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

后面查了下,原来这是GCC 编译器的扩展特性下的嵌套函数(nested function)特性,标准 C(C89/C99/C11 等)并不支持函数嵌套定义,因此这段代码只能在 GCC下编译运行。