How to compile a C project in C99 mode?

后端 未结 4 2008
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 17:03

I got the following error message while compiling the C code:

error: \'for\' loop initial declarations are only allowed in C99 mode
note: use option -std=c9         


        
相关标签:
4条回答
  • 2020-12-14 17:44

    The other answers give you a work around to deal with GCC's default mode. If you'd like to use C99, (which I do recommend in general) then you have to add that compiler flag:

    gcc -std=c99 foo.c -o foo
    

    Or, if you're using a standard makefile, add it to the CFLAGS variable.

    0 讨论(0)
  • 2020-12-14 17:56

    It means you can't declare variables in for statement.

    You should do:

    int i ;
    for( i = 0 ; i < len ; i++ )
    

    What you are probably doing

    for( int i = 0 ; i < len ; i++ )
    
    0 讨论(0)
  • 2020-12-14 17:57

    You have done this:

    for (int i=0;i<10;i++) {
    

    And you need to change it to this:

    int i;
    for (i=0;i<10;i++) {
    

    Or, as the error says,

    use option -std=c99 or -std=gnu99 to compile your code.

    Update copied from Ryan Fox's answer:

    gcc -std=c99 foo.c -o foo
    

    Or, if you're using a standard makefile, add it to the CFLAGS variable.

    0 讨论(0)
  • 2020-12-14 18:03

    You'll still need C99 if you want to mix statements and variable declarations. As other answers and the error message itself say, add -std=c99 to the command-line when you compile to enable C99 features [1].

    But you have always been allowed to write a compound statement (a "block", IOW, but the standard never uses this word!) in place of a single statement.

    #include<stdio.h>
    int main() {
        int i = 5;
    
        {   /* new block, new declarations. */
            int i;
            for (i=0;i<10;i++){
            }
        }
        printf("%d\n", i);  /* prints "5\n" */
    }
    

    This is legal in K&R, C90 (aka C89, it's the same thing), and C99.

    Enabling C99 mode gets you lots of cool stuff, but it also disables some other cool stuff that gcc allows by default, like anonymous structures and unions within structures and unions.

    1. -std=gnu99 probably enables "all the goodies", but I caution you to avoid doing this. It will make unnecessary difficulty if you (or others) wish to port the code. I'd probably have a windows version of my pet project, ported for free by somebody, had I not done this very thing. It ties you gcc. You don't want to be tied. That's the whole bloody point of standards.
    0 讨论(0)
提交回复
热议问题