How to compile a C project in C99 mode?

☆樱花仙子☆ 提交于 2019-11-27 13:39: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=c99 or -std=gnu99 to compile your code

What does it mean?

How to fix it?


回答1:


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.




回答2:


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.



回答3:


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.




回答4:


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++ )


来源:https://stackoverflow.com/questions/15870567/how-to-compile-a-c-project-in-c99-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!