简体   繁体   中英

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

I would like if anyone knows how to force gcc to fail the current compilation if a variable isn't declared at the top of the function.

void foo() {

  int bar; //Enabled

  /* some code stuff */

  int bar2; //Compile Error
}

I've already seen that I need to compile with -pedantic && -ansi . It's already the case for my project, but it doesn't seems to work.

BTW I am compiling in C89 and really need to stay in that C version. ( -ansi )

On all the docs that I've seen, there is no gcc flag that allow to do it. Is there something I've missed.

There's an option to warn about variables defined or declared after statements:

  • -Wdeclaration-after-statement — warning unless you've also set -Werror (and it is a good idea to use -Werror at all times; you won't forget to fix the warnings!)
  • -Werror=declaration-after-statement — error even if you've not set -Werror

This forces variables to be defined at the top of any statement block (as required by C90) rather than allowing variables to be declared when needed (as allowed by C99 and beyond). This disallows:

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;
}

There isn't an option that I know of that prevents you declaring variables after the { of an inner block in a function.

-pedantic will only issue diagnostics for cases for which the standard requires that they're issued. These are warning only. Presumably you would have your desired behaviour with -pedantic-errors when combined with -ansi -std=c90 ;)

Example:

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

And then:

% 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

but with -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

The version is

% 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.

Note that even ISO C90 does not require that the declarations be at the top of a function - beginning of any compound statement will do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM