如果变量不在函数的顶部,则禁用变量声明

Disabling variable declaration if they are not at the top of the function

如果有人没有在函数顶部声明变量,我想知道如何强制 gcc 使当前编译失败。

void foo() {

  int bar; //Enabled

  /* some code stuff */

  int bar2; //Compile Error
}

我已经看到我需要使用 -pedantic && -ansi 进行编译。 我的项目已经是这样了,但是好像不行。

顺便说一句,我正在 C89 中编译,确实需要留在那个 C 版本中。 (-ansi)

在我看过的所有文档中,没有允许执行此操作的 gcc 标志。 有什么我遗漏的吗?

-pedantic 只会针对标准 要求 发布的情况发布 诊断 。这些只是 警告。据推测,当与 -ansi -std=c90 ;)

结合使用时,-pedantic-errors 会出现你想要的行为

示例:

#include <stdio.h>
int main(void) {
    printf("Hello Stack Overflow\n");
    int fail;
}

然后:

% gcc test.c -ansi -pedantic
test.c: In function ‘main’:
test.c:4:3: warning: ISO C90 forbids mixed declarations and code 
       [-Wdeclaration-after-statement]
   int fail;
   ^~~
% ./a.out
Hello Stack Overflow

-pedantic-errors:

% gcc test.c -ansi -pedantic-errors
test.c: In function ‘main’:
test.c:4:3: error: ISO C90 forbids mixed declarations and code         
       [-Wdeclaration-after-statement]
   int fail;
   ^~~
% ./a.out
bash: ./a.out: No such file or directory

版本是

% gcc --version
gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0
Copyright (C) 2017 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.

请注意,即使 ISO C90 也不要求声明位于 函数 的顶部 - 任何 复合语句 的开头都将做。

有一个选项可以警告在语句之后定义或声明的变量:

  • -Wdeclaration-after-statement — 警告,除非您还设置了 -Werror(始终使用 -Werror 是个好主意;您不会忘记修复警告!)
  • -Werror=declaration-after-statement — 即使您没有设置 -Werror
  • 也会出错

这会强制在任何语句块的顶部定义变量(如 C90 所要求的),而不是允许在需要时声明变量(如 C99 及更高版本所允许的)。这不允许:

int function(int x)
{
    int y = x + 2;
    printf("x = %d, y = %d\n", x, y);
    int z = y % x;     // Disallowed by -Wdeclaration-after-statement
    printf("z = %d\n", z);
    return x + y + z;
}

据我所知,没有一个选项可以阻止您在函数内部块的 { 之后声明变量。