Reputation: 113
Sorry if this is a noobish question, but here it is anyway.
So I followed this tutorial on MSDN about creating and using static libraries.
Let's assume you have a Static Library fooLib
, and a Program barExec
, that uses fooLib
According to the tutorial, or at least my interpretation of it, in the source code for barExec
, you have to #include
the header file used to compile fooLib
(fooLib.h
, in my case).
So the code that I have in barExec
is as follows:
// barExec.cpp
#include <iostream>
#include "fooLib.h"
// Rest of my program here.
My question is, Why should I bother going through all the extra hassle of creating fooLib
in the first place, especially since I had to write fooLib.cpp
anyway? Is there a benefit to creating the fooLib
library, when I could just #include "fooLib.h"
directly?
Upvotes: 1
Views: 1006
Reputation: 103703
You have a false dichotomy in your question. A static library is not an alternative to a header. There are, off the top of my head, 3 alternatives to a static library.
In all cases, you still need your headers (or alternatively, you can just declare the functions and types you need to use, if there aren't too many, and you know the right signatures).
Option 2 is essentially what a static library is. The only difference is, that the object files are conveniently packed up into a single file. This makes distributing and using the library at least a little bit easier. For example, if you have a library with 10 object files which you want to use, linking it might look something like this:
g++ main.o foo1.o foo2.o foo3.o foo4.o foo5.o foo6.o foo7.o foo8.o foo9.o foo10.o
whereas if you put it in a static library, the linking invocation might look a lot simpler:
g++ main.o -lfoo
Option 3 is the precursor to option 2. If you have one or more c++ source files, after you compile them, you will have one or more object files (although most toolchains will allow you to combine the compiling and linking into one step, in which case no object files will appear on disk). If you have a large library that you plan to use in many projects, you may not want to recompile it for every one of those projects. So you may opt for option 2. And if that results in a lot of object files, you may find it convenient to opt for a static library.
Upvotes: 5
Reputation: 206577
A header file provides the declarations of functions and variables only. It does not provide the implementations of the functions and definitions of variables. The latter can be found in another .cpp file or a library, which can be a static library or a dynamic library.
Upvotes: 0