Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best header structure to use in a library?

Tags:

c++

header

Concerning headers in a library, I see two options, and I'm not sure if the choice really matters. Say I created a library, lets call it foobar. Please help me choose the most appropriate option:

  1. Have one include in the very root of the library project, lets call it foobar.h, which includes all of the headers in the library, such as "src/some_namespace/SomeClass.h" and so on. Then from outside the library, in the file that I want to use anything to do with the foobar library, just #include <foobar.h>.

  2. Don't have a main include, and instead include only the headers we need in the places that I am to use them, so I may have a whole bunch of includes in a source file. Since I'm using namespaces sometimes as deep as 3, including the headers seems like a bit of a chore.

I've opted for option 1 because of how easy it is to implement. OpenGL and many other libraries seem to do this, so it seemed sensible. However, the standard C++ library can require me to include several headers in any given file, why didn't they just have one header file? Unless it's me being and idiot, and they're separate libraries...

Update:

Further to answers, I think it makes sense to provide both options, correct? I'd be pretty annoyed if I wanted to use a std::string but had to include a mass of header files; that would be silly. On the other hand, I'd be irritated if I had to type a mass of #include lines when I wanted to use most of a library anyway.

Forward headers:

Thanks to all that advised me of forward headers, this has helped me make the header jungle less complicated! :)

like image 373
Nick Bolton Avatar asked Dec 03 '22 15:12

Nick Bolton


2 Answers

stl, boost and others who have a lot of header files to include they provide you with independent tools and you can use them independently.

So if you library is a set of uncoupling tools you have to give a choice to include them as separate parts as well as to include the whole library as the one file.

like image 97
Mykola Golubyev Avatar answered Dec 09 '22 15:12

Mykola Golubyev


Think a bit about how your libary will be used, and organize it that way. If someone is unlikely to use one small part without using the whole thing, structure it as one big include. If a small part is independent and useful on its own, make sure you can include just enough for that part. If there's some logical grouping that makes sense, create include files for each group.

As with most programming questions, there's no one-size-fits-all answer.

like image 27
Mark Ransom Avatar answered Dec 09 '22 16:12

Mark Ransom