I am currently writing a C (not C++). It seems the Microsoft's C compiler requires all variables to be declared on top of the function.
For example, the following code will not pass compilation:
int foo(int x) {
assert(x != 0);
int y = 2 * x;
return y;
}
The compiler reports an error at the third line, saying
error C2143: syntax error : missing ';' before 'type'
If the code is changed to be like below it will pass compilation:
int foo(int x) {
int y;
assert(x != 0);
y = 2 * x;
return y;
}
If I change the source file name from .c
to be .cpp
, the compilation will also pass as well.
I suspect there's an option somewhere to turn off the strictness of the compiler, but I haven't found it. Can anyone help on this?
Thanks in advance.
I am using cl.exe that is shipped with Visual Studio 2008 SP1.
Added:
Thank you all for answering! It seems I have to live in C89 with Microsoft's cl.exe.
The C/C++ compiler compiles each source file separately and produces the corresponding object file. This means the compiler can only apply optimizations on a single source file rather than on the whole program. However, some important optimizations can be performed only by looking at the whole program.
Show activity on this post. This is a tradition which comes from early C compilers, when compiler needs all local variable definitions before the actual code of function starts (to generate right stack pointer calculation).
The C/C++ compiler compiles each source file separately and produces the corresponding object file. This means the compiler can only apply optimizations on a single source file rather than on the whole program.
On the other hand, the Visual C++ compiler can spend a lot more time to spot other optimization opportunities and take advantage of them. A great new technology from Microsoft, called .NET Native, enables you to compile managed code into self-contained executables optimized using the Visual C++ back end.
It looks like it's using C89 standard, which requires that all variables be declared before any code. You may initialize them with literals, etc., but not mix code and variables.
There should be a compiler flag to enable C99 somewhere, which will get you the behavior you're used to.
EDIT: quick Googling does not look promising for enabling C99. You may have to live with C89 (which ain't so bad) or find a better C compiler (which would be better).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With