0

I am trying to use stb_image to load image files as textures in an OpenGL program, the documentation of the header file stb_image.h states the following:

"Do this:

#define STB_IMAGE_IMPLEMENTATION

before you include this file in one C or C++ file to create the implementation."

What does this type of preprocessor directive actually do?

For the benefit of the reader, here is how my project is structured.

  1. main.cpp
  2. stb_image.h

The header of the main.cpp file looks likes this:

#include <iostream>
#include <glad/glad.h>
#include <glfw3.h>
#include "shader.h"

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
A. Khaled
  • 168
  • 1
  • 10
  • Why not look at the file `stb_image.h` itself to see what it does when the macros is defined? – Some programmer dude Oct 02 '20 at 12:08
  • 3
    This is a 'common' pattern in 'header only libraries', to follow the one definition rule stuff needs to be appear in at most one .cpp file, therefore the library asks you to put #define WTV before including the file in at most one cpp this will enable the implemention in that file, all the other places will only have the declaration. [tinyobjloader](https://github.com/tinyobjloader/tinyobjloader) works like this too. – Borgleader Oct 02 '20 at 12:16
  • @Someprogrammerdude I did but I couldn't really understand much what was going on, I am new to using 3rd party libraries so I didn't know what to look for, but I think Borgleader's answer sums it up well. Thank you both. – A. Khaled Oct 02 '20 at 12:19
  • 1
    @A.Khaled if you open the [std_image.h](https://github.com/nothings/stb/blob/master/stb_image.h) and go down to line 514. you can see ``#ifdef STB_IMAGE_IMPLEMENTATION`` this mean that if the macro ``STB_IMAGE_IMPLEMENTATION`` is defined the following lines will execute. This allow openGL to enable some things but this would need to look more specifically at openGL code – Dzious Oct 02 '20 at 12:30
  • Question has been answered, but voting this one as duplicate anyway: [Preventing multiple #define when including headers](https://stackoverflow.com/questions/64058036/preventing-multiple-define-when-including-headers) – Botje Oct 02 '20 at 12:50

0 Answers0