SJWard
SJWard

Reputation: 3739

Why does the same header file have to be included twice?

I've just finished building a program in which I have a main.cpp file and my own static library, let's call it myLib and it's made from myLib.h and a myLib.cpp files.

myLib.h and myLib.cpp make a static library.

In my static library, I make use of some boost functions and classes so as my own classes and functions in myLib.cpp can do some things: so in myLib.cpp I add the lines

#include <boost/math/distributions/binomial.hpp>
#include <boost/math/tools/roots.hpp>

to myLib.cpp

Now myLib.h contains function declarations, and some class definitions, myLib.cpp has the implementation of those functions and class definitions, and since some of the functions, require the classes declared in myLib.h, #include "myLib.h" must also be added to the myLib.cpp file (I suspect that if those functions did not, then myLib.cpp could be compiled as an object file without the myLib.h file needing to be included so long as whatever uses the object file does include myLib.h - but since some functions use the classes, myLib.cpp also includes myLib.h). Is it acceptable for the implementation file to require the header file for compilation as an object file (and then inclusion into a .a file)? I can't quite fathom if this is bad or not - I thought the idea was they are supposed to be separate?

Upvotes: 1

Views: 322

Answers (3)

tsragravorogh
tsragravorogh

Reputation: 3153

If you are implementing your class in 2 different (head and source) files (which is normally the case), then yes, you absolutely HAVE to include header file in your source file. If your class is really light, then you can just implement your function within the header file. This is bad practice and not really recommended, so I would not recommend that either. Especially in the case of a static library, where you are supposed to give out the header files to other modules in order to make use of it. You do not want the library consumer to see any source code.

Upvotes: 1

Andrei Bozantan
Andrei Bozantan

Reputation: 3921

In C++ it is totally acceptable to include the header file which contains the class declaration in the source file which contains the implementation. If you think more this is normal because the implementation (cpp file) will have no other way how to know about the fields (variables) in the class.

Upvotes: 1

Paul Evans
Paul Evans

Reputation: 27567

This is totally normal and the way things are done in C/C++. The header file contains all the declarations needed to use the library, the source file contains the definitions needed to build the library. This source file includes the header file as classs, functions, etc need to be declared before they can be defined.

Upvotes: 2

Related Questions