Reputation: 413
I want to use stb_image library, which the author has put into a very large header file. To use the library, the documentation tells me to add these 2 lines to my code.
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
I did just that, putting it into a header file; I even made sure that it has include guard.
#ifndef STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#endif
The linker complained however.
I look up and find the solution. https://github.com/nothings/stb/issues/3
Basically, I have to add the two lines above to the cpp file and not header file. It works like a charm. But why is header guard not effective in this way? I have been reading about translation units and statics yet I could not understand why my method would not work.
Upvotes: 0
Views: 882
Reputation: 30579
stb_image.h has its own include guards. That's not what defining STB_IMAGE_IMPLEMENTATION
is for. Defining STB_IMAGE_IMPLEMENTATION
tells stb_image.h to include not only declarations, but also definitions for its functions and variables into that translation unit. If stb_image.h is included into multiple translation units with STB_IMAGE_IMPLEMENTATION
defined, then all of those translation units will have definitions for stb_image's functions and variables, and the One Definition Rule is violated.
Upvotes: 3