c++duplicate-symbolheader-onlynested-includes

Duplicate symbols error when including file that includes stb_image.h


In my main.h file, I #include "skybox.h". In skybox.h, stb_image.h is included (the latest version from GitHub as of 29-1-2017). Unlike any other library I've encountered, before including stb_image.h the docs say to #define STB_IMAGE_IMPLEMENTATION. I have tried putting this before including stb_image.h (in skybox.h), before including skybox.h (in main.h), both, and none. None of them work, the linker outputs all the duplicates from between build/main.o and build/skybox.o.

ld: 33 duplicate symbols for architecture x86_64

is the error given when linking. Also, I am doing the #define from the header file stb_image.h, but have tried doing it from the source file, which does not help.


Solution

  • I finally figured out how to fix it. Instead putting #define STB_IMAGE_IMPLEMENTATION and #inlclude stb_image.h in the header file, you put them in the source file wherever they are used. If you put #define STB_IMAGE_IMPLEMENTATION in the header, it gets defined in all the files that include that header, causing the duplicate symbols error as when it is defined, stb_image gets reimplemented.