5

Is it considered good practice to structure single-file/header-only libraries in C++ such that they are conditionally either the header or the implementation? For example,

#ifndef LIBRARY_HEADER_HPP_
#define LIBRARY_HEADER_HPP_

// Header

struct Test {
    void test(); 
};

#endif // LIBRARY_HEADER_HPP_

#ifdef LIBRARY_IMPLEMENTATION_
#undef LIBRARY_IMPLEMENTATION_

// Implementation

void Test::test() {

}

#endif // LIBRARY_IMPLEMENTATION_

The user of the library would therefore #define LIBRARY_IMPLEMENTATION before one #include "Library.hpp" in a single implementation file, to avoid multiple definitions.

I've seen this strategy used in C libraries (STB comes to mind), but I was wondering whether this would be considered idiomatic in modern C++ (or if there are better strategies for creating single-file/header-only libraries).

AUD_FOR_IUV
  • 473
  • 1
  • 3
  • 16
  • 3
    What problem is this supposed to solve? – Pete Becker Jan 04 '17 at 03:16
  • Who does single header libraries in modern C++? – dtech Jan 04 '17 at 03:19
  • @PeteBecker I suppose ease of use (drop and go, instead of integrating sources into a build system). – AUD_FOR_IUV Jan 04 '17 at 03:51
  • @ddriver Whenever templates are used (which have to go in headers) – AUD_FOR_IUV Jan 04 '17 at 03:52
  • @AUD_FOR_IUV: Integrating sources into build systems? It's a `.cpp` file. It doesn't even have to be a static library. If a user can't manage to add a source file to their build system, they've got bigger problems than using your library. – Nicol Bolas Jan 04 '17 at 04:14
  • 1
    @NicolBolas So is there simply no use at all? Are libraries like the aforementioned STB not worth constructing in such a way? – AUD_FOR_IUV Jan 04 '17 at 04:26
  • I think its not future oriented. Sooner or later there will be modules, without any preprocessor, which require each header to be separated. – Trevir Jan 04 '17 at 09:18

0 Answers0