c++visual-studio-2008header-files

What MSVC++ 2008 Express Editon compiler does and doesn't


I've been wondering if the msvc++ 2008 compiler takes care of multiple header includes of the same file, considering this example:
main.cpp

#include "header.h"
#include "header.h"

Will the compiler include this file multiple times or just one? (I'm aware I can use the #ifndef "trick" to prevent this from happening) Also, if I include "header.h" which contains 10 functions, but I only call or use 2, will it still include all 10 or just the 2 I need and all of their needs?


Solution

  • No, the compiler (or, more accurately, the pre-processor) doesn't take care of this "automatically". Not in Visual C++ 2008, or in any other version. And you really wouldn't want it to.

    There are two standard ways of going about this. You should choose one of them.

    The first is known as include guards. That's the "#ifndef trick" you mentioned in your question. But it's certainly not a "trick". It's the standard idiom for handling this situation when writing C++ code, and any other programmer who looks at your source file will almost certainly expect to see include guards in there somewhere.

    The other takes advantage of a VC++ feature (one that's also found its way into several other C++ toolkits) to do essentially the same thing in a way that's somewhat easier to type. By including the line #pragma once at the top of your header file, you instruct the pre-processor to only include the header file once per translation unit. This has some other advantages over include guards, but they're not particularly relevant here.

    As for your second question, the linker will take care of "optimizing" out functions that you never call in your code. But this is the last phase of compilation, and has nothing to do with #include, which is handled by the pre-processor, as I mentioned above.