Hacker News new | ask | show | jobs
by noobermin 2378 days ago
Hijacking your comment to ask my question below. Apart from the possibility you can't do header-only for everything (like something that requires a singleton for example) and the other known issues (build times, ballooning of object files and thus executables) is the only other reason you don't see as many header-only libraries in C (like you do in C++ where they are ubiquitous) is that people merely don't do it in C? That is, a social landscape reason, not a technical reason.
4 comments

It's partly a historical reason as well. There are many projects with very complex Makefiles. Those are hard to integrate into your own project.

Header-only is the other extreme: No makefile at all. With package managers like Conan and vcpkg, using a build-system like e.g. CMake, it's possible to have very simple and short project files which are easy to integrate.

In this regard, C and C++ are a bit behind the times compared to other languages.

Isn't C++ supposed to be getting proper namespaces soon?
I am not an expert in C++, but there exists an opinion that it will not help as much as you might think.

https://cor3ntin.github.io/posts/modules/

The solution for the "singleton problem" is to put the implementation code into a separate part of the header behind an #ifdef XXX_IMPL, and only define this before including the header in one place in the project.

This is also the approach used by this library, see:

https://github.com/jeremycw/httpserver.h#example

This approach also doesn't have the 'build time problems', since the (expensive to compile) implementation code is only seen once by the compiler (unlike many C++ header-only libs, which rely on inline code)

The fact that you cannot define templates out of headers also explains why C++ has a lot of header-only libraries. : if you use templates and have no global references, you are most likely already header-only.
Yeah, templates forces many C++ libraries to be header only. I suspect this came first, and only after a c++ header-only (because they had to be) libraries existed did people realize there were advantages to header only and so people wrote them where they wouldn't have to.
Yes, the social reasons are the only ones, besides the technical reasons :)

An additional technical downside in this case is the code complexity in the client code, from the required modal preprocessor flags.