Tutorial :Visual Studio 2008 compiles anything in C++ file?


I noticed today that a source code file in a project was compiling even though it had junk at the top of it. It got me wondering what all would pass without error through the compiler. Here is an example of code that will not generate any error messages:

what kind of weird behaviour is this???    #include "stdafx.h"    // what is up?    int foo(int bar)  {      bla bla bla?????      return bar;  }    and more junk???  

What in the world is the compiler doing to allow this code to compile without giving any error messages? I'm using Visual Studio 2008 and this is unmanaged C++ code. The foo function isn't actually generated in the object file so it can't be used but why no errors???


The part before the #include "stdafx.h" line is actually explainable (given that the file is actually compiled): everything before and including that line is ignored if precompiled headers are enabled (which is the default). See Wikipedia on Precompiled Headers for a short summary.

However, if syntactically wrong code below that include is not generating errors it's likely your file isn't getting compiled at all.


It does not compile anything ;) Your file probably just isn't included in the project.


"The foo function isn't actually generated in the object file so it can't be used"

This should be your hint it's not being compiled. Why would the compiler "compile" something for no output?

Either it's not included, you're looking at the wrong file (technically a variation of the previous), or it has the same name as another source file in the project, in which case only one will be compiled.


If I have any suspicions that a file is not being compiled I start inserting:

#pragma message("Reached Here!")  

type lines in the source until I see the message pop up.

I've tested the source code from the OP with VS2008 in a project that uses precompiled headers and bluebrother is correct that text before the first #include is ignored, including #pragma message.


Your file is probably just not being compiled.

OTOH, VC++ would seem to accept this if it was in a template (that is not instantiated)

template <class T>  T foo(T bar)  {      bla bla bla?????      return bar;  }    int main()  {  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »