Hacker News new | ask | show | jobs
by sp1rit 888 days ago
You'd still have to parse & compile the contents of the header for each translation unit, instead of only once.
1 comments

In STB-style headers the implementation is inside a separate ifdef/endif block which is only activated at a single include point in the whole project. At all other include points the compiler will only parse the public API declarations and skip the implementation block (which is so much faster than parsing and compiling the implementation that the difference to a header which only contains the API declaration doesn't matter much even in large projects).

For instance here is the start of the implementation block in stb_image.h, above that is just "cheap" public API declarations:

https://github.com/nothings/stb/blob/f4a71b13373436a2866c5d6...

While I'm a big fan of keeping declarations and implementations as close as possible, I find that the need to explicitly #define STB_SOMETHING_IMPLEMENTATION before including the header somehow spoils the simplicity of the solution. At this point, I'd rather use a single file that acts as either a .h or a .c based on __INCLUDE_LEVEL__ (a GCC extension, not sure if available for MSC).