Structuring Single-File/Header-Only Libraries in C++

1.6k views Asked by At

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).

0

There are 0 answers