Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 664
Dan Avatar asked Mar 08 '09 14:03

Dan


People also ask

Do you need to compile header files C?

You don't need to compile header files. It doesn't actually do anything, so there's no point in trying to run it. However, it is a great way to check for typos and mistakes and bugs, so it'll be easier later.

Why include header files instead of C files?

c files to a compiler, and the C source files include the header files to get needed function and type declarations. Since actual function definitions (Aside from the occasional inline one) don't show up in header files, there's no point to having the compiler compile them directly.

Do static libraries need header files?

You can have the libraries installed without the headers. You can't then compile code that uses the header, but you can run code that uses the shared library.

Can we write the executable code in header file?

h. DON'T include any executable lines of code in a header file, including variable declarations. But note it is necessary to make an exception for the bodies of some inline functions, about which more below.


2 Answers

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();
}
like image 102
sharkin Avatar answered Sep 21 '22 20:09

sharkin


Even when you will create a .cpp file you still won't receive anything. You need to instantiate templates in order to put them in the library.

Take a look here http://www.parashift.com/c%2B%2B-faq-lite/templates.html#faq-35.13 about how to instantiate templates with concrete types.

like image 23
Mykola Golubyev Avatar answered Sep 23 '22 20:09

Mykola Golubyev