Compiling a C++ .lib with only header files?

Dan picture Dan · Mar 8, 2009 · Viewed 7.8k times · Source

I'm compiling a C++ static library and as all the classes are templated, the class definitions and implementations are all in header files. As a result, it seems (under visual studio 2005) that I need to create a .cpp file which includes all the other header files in order for it to compile correctly into the library.

Why is this?

Answer

sharkin picture sharkin · Mar 8, 2009

The compiler doesn't compile header files since these are meant to be included into source files. Prior to any compilation taking place the preprocessor takes all the code from any included header files and places that code into the source files where they're included, at the very location they're included. If the compiler should compile the headerfiles as well, you'd for example have multiple definitions on many things.

Example, this is what the preprocessor sees:

[foo.h]
void foo();

--

[mysource.cpp]
#include "foo.h"

int main()
{
   foo();
}

And this is what the compiler sees:

[mysource.cpp]
void foo();

int main()
{
   foo();
}