Preventing multiple #define when including headers

后端 未结 3 965
暖寄归人
暖寄归人 2021-01-27 08:07

coming from python and am a bit tripped up on what the proper approach to this is.

I am trying to include this library in my project: https://github.com/nothings/stb/blob

相关标签:
3条回答
  • 2021-01-27 08:42

    Create a cpp file (or whatever extension you are using for your source files) whose sole purpose is to have

    #define STB_IMAGE_IMPLEMENTATION
    
    #include <stb_image.h> 
    

    and don't forget to include this cpp file into your project so that it is compiled and the result is linked into your program. In all other places where you need something from this library, just include the stb_image.h header as usual.

    These "implementation" macros are a "trick" used by some library authors to make "installing" their library easy. The idea is that when a specific macro (chosen by the library authors) is defined before the header of that library is included, some code with the actual implementation will be added. That is why this must be in a source file instead of a header and only in one source file (otherwise you get multiple definitions for the same functions).

    0 讨论(0)
  • 2021-01-27 08:49

    #define is a preprocessor directive and doesn't actually get run everytime the header is accessed so you should 't have any problems

    if you are using visual studio you can also do #pragma once to only parse the file once stopping anything from happening twice

    0 讨论(0)
  • 2021-01-27 09:07

    You should have the #define STB_IMAGE_IMPLEMENTATION macro definition in exactly one source file that includes <stb_image.h> (a .cpp file, not in a header).

    Since you can also only have one source file that defines main(), it is simple to put the #define in the same file as main() (as long as it also includes <stb_image.h>), but it can be used in any other source file if you prefer. You could even create a source file stb_image_imp.cpp that contains just the two lines shown, and link that into your program (or library) too.

    All other source files in the project should only include <stb_image.h> without also defining the macro.

    0 讨论(0)
提交回复
热议问题