Hacker News new | past | comments | ask | show | jobs | submit login

That's why you wrap the function implementations in an #ifdef and instruct the library user to set the corresponding define in exactly one place, like the list maintainer does in his own single header libraries: https://github.com/nothings/stb/blob/b42009b3b9d4ca35bc703f5...



Sure, that's an option.


It’s not just an option, that’s how most header only libraries are explicitly created.


I haven't used a single C++ header-only library which required a #define. But that's because in C++ the "inline" keyword creates a weak symbol, so you can #include a header in several places and there will only ever be a single implmentation. For function templates this happens automatically, btw.

IMO, if you need a #define like this, you're are not really writing a header-only library, that's basically just a source file in disguise. You could just as well distribute headers + a single source file and just ask the user to add this one source file to their build system (which should really be a trivial task).

EDITED for more clarity about C vs C++.


Also, while it's easier to just include another header file, it can have a pretty serious impact on build times. If you compare the same program with header-only libraries to one with libraries using the normal header declaration/source definition split, it's much faster. I never worried about this too much in C, but C++ takes long enough to build as it is.

<grumble>

As a sidenote, I remember my brain hurting when I learned about C++ just redefining `inline`. It would have made much more sense to just define a new keyword.

</grumble>


Personally, I think people should only do C++ header-only libraries if technically necessary (e.g. heavy reliance on templates). Otherwise it just unnecessarily hurts compile times, as you've correctly noted, because the compiler still has to parse all those "inline" functions.


I don't disagree. My top comment was that if you are maintaining a list of single-header libs, might also pay attention to whether they are implemented properly.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: