0

A header library is a library with all the code in the header.

If I have two cpp files that need code from the header lib, and if they both import the header, and both get compiled, the header file is getting compiled twice, I think. Would linking now throw and error because the header lib functions are being defined twice? If not an error, is this still bad practice?

What is the correct way to handle a header lib?

Thomas
  • 6,032
  • 6
  • 41
  • 79

2 Answers2

1

Just #include everywhere you want. If the library is not horribly broken, it will work fine. The library itself is responsible for having mechanisms that make it usable, in case of a header only library that means making it usable by including the header(s).

Nothing would make this bad practice, simply using by including is the purpose of a header only library.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
0

Header files will use include guards (Include Guard wiki) that keep library functions from being defined twice. Basically, a header file will use a conditional statement that is evaluated during compilation that checks for an existing library definition. If it is defined already it ignores anymore additional definitions. These guards look like this:

/* library_name.h  */
#ifndef SOME_IDENTIFIER
#define SOME_IDENTIFIER
   [function prototypes]
#endif

A Daniel's Computer Blog article (Here) provides a very digestable explanation of what's going on behind the scenes and flushes out more nuances that I didn't address.

Baum mit Augen is right. If the lib uses include guards there will be no problem using #include<library_name> anywhere you want as many times as you want.

Ideally you will use #include<library_name> once at the top of any file that uses a function/class/constant from the library.

Alex Edwards
  • 328
  • 1
  • 2
  • 8