2

I've spent some time developing a header-only library and have stumbled across a crossroads. Everywhere I look on the web, inline functions are always used. But in the example of stb_image.h, the source code is just written in the bottom half of the header surrounded by a #ifdef STB_IMAGE_IMPLEMENTATION like so:

#ifndef STB_IMAGE_H_INCLUDED_
#define STB_IMAGE_H_INCLUDED_

void some_func(args);

#endif // STB_IMAGE_H_INCLUDED_

#ifdef STB_IMAGE_IMPLEMENTATION

void some_func(args) {
    // implementation
}

#endif // STB_IMAGE_IMPLEMENTATION;

Then a (preferably source that isn't main.cpp) file defines a macro with the same name and includes the header right after like so:

#include <…>
#include <…>

#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>

// other code

Why would you use one over the other? (or rather why does stbi do this at all?)

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
J. Lengel
  • 570
  • 3
  • 16

1 Answers1

4

STB is a C library. C inline was introduced in C99, and don't work like C++ inline. C inline still must be implemented in one translation unit only.

C++ inline is used to make exception in the ODR rule, and allow multiple implementation as long as they are the same.

STB wants to be a header only library, but they don't really exist in C, so they used a macro based solution to only implement the code in a choosen translation unit.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • So stbi can't use it because inline doesn't allow for multiple definitions in c? – J. Lengel Jun 10 '19 at 16:30
  • @J.Lengel Well, one would include the header *everywhere* needed – but only once with the macro defined. I personally consider this inferior to just providing separate source files, though... – Aconcagua Jun 10 '19 at 16:35
  • @J.Lengel C++ once used the same definition for `inline` as C still does today: A hint for the compiler to inline the function (not mandatory), i. e. avoid function call overhead and just place the function code directly everywhere the function is called. Having such a function in a header then requires you to have it `static inline` such that it is not visible outside the compilation unit. That meaning was dropped in the meanwhile (not in C, though), as the people considered the compiler smarter than the coder to decide if better inlining a function or not... – Aconcagua Jun 10 '19 at 16:48
  • I knew that but I just wanted to know why stbi used that starnge macro. (You explained that though) – J. Lengel Jun 10 '19 at 16:51