4 ms·
nothings' guide on how to write single-file libraries is informative if you want to write your own: https://github.com/nothings/stb/blob/master/docs/stb_howto.t
by sxp 6y ago
nothings' guide on how to write single-file libraries is informative if you want to write your own: https://github.com/nothings/stb/blob/master/docs/stb_howto.txt https://github.com/nothings/stb/blob/master/docs/stb_howto.t...
- spacechild1 6y agoUsing something like #define LIBRARYNAME_IMPLEMENTATION is a hack that is only necessary for C, because in C++ you can just mark all functions "inline" and there will only ever be a single implementation, no matter how often you include it.
- flohofwoe 6y agoPlease don't, inline code in headers is the single reason why C++ compiles so slowly, and besides: the inline keyword is also available in C (since C99), but that doesn't mean it's a good idea to use it: The IMPLEMENTATION define cleanly separates the public API declarations (which are required in each source file where functions from this library are called), from the implementation code and any implementation-private declarations. If you put all the implementation code into inline code, this code is parsed over and over again in each source file which would only need to include the declarations. This is the main reason why C++ projects compile so slowly, and what gives "header-only libraries" such a bad reputation in the C++ world. "STB-style single file libraries" don't suffer from this problem.
- spacechild1 6y ago> the inline keyword is also available in C (since C99) but it doesn't work the same way. > If you put all the implementation code into inline code, this code is parsed over and over again in each source file That's true. Good header-only C++ libraries provide "forward" headers, which you can use if you don't need the full definition. But the best thing is to only write C++ header-only libraries if there is a technical reason (e.g. heavy templated code). > "STB-style single file libraries" don't suffer from this problem. That's right, but I also don't see the benefit. To me, telling the user to add a #define to some random source file feels incredibly hacky. On a technical level, it's the same as asking the user to #include a ".c" file. Why not put the implementation in a single ".c" file, which the user can add to their project? I honestly don't understand this...