Unexpected compile error for trivial code
I have come across a weird compiler error (using VC2010) while trying to compile a library (flextGL), which makes absolutely no sense to me.
Consider the following minimal C example (test.c
):
void a()
{
// ...
}
int b()
{
a();
int c;
return 0;
}
If I try to compile this under VC2010, I get the following error:
test.c(10) : error C2143: syntax error : missing ';' before 'type'
The error is referring to the int c;
line.
After some experimenting, I found the following as well:
- If I remove the
int c;
line, it compiles fine. - If I remove the
a();
line, it compiles fine. - If I move the
int c;
line above thea();
line, it compiles fine. - If I rename the file to be compiled as C++ instead of C (
.cpp
instead of.c
), it compiles fine.
Why is this weird error occurring?
My only guess is this is one of those archaic features of C, where all variables have to be declared at the top of a function. But I would have th开发者_如何学Cought that modern compilers were smarter than that.
Your guess is correct.
You declared a variable after a non-variable declaration in a block. Visual C++ does not implement C99 but only ANSI C so that does not compile.
The C Compiler included with VC2010 is from an older version of the standard, in which variables could only be declared at the top of a scope.
Because you are compiling with Visual C++ and Microsoft doesn't support C99. It supports C89 which means you have to declare all variables at the top of the scope.
With gcc and warnings enabled, I get:
gcc -Wall --pedantic foo.c -c
foo.c:3:5: warning: C++ style comments are not allowed in ISO C90
foo.c:3:5: warning: (this will be reported only once per input file)
foo.c: In function ‘b’:
foo.c:10: warning: ISO C90 forbids mixed declarations and code
foo.c:10: warning: unused variable ‘c’
Maybe you should enable all warnings for your compiler too, to get more informations.
In C all variables do need to be declared at the beginning of a block. The memory for variables (in your case 4 bytes) gets added to the stack as you enter a new function and removed as you exit the function.
If you need to declare a variable elsewhere you can always use an inline function like this.
int b()
{
a();
{
int c;
}
return 0;
}
精彩评论