I
I
IliaNeverov2021-07-13 13:10:48
C++ / C#
IliaNeverov, 2021-07-13 13:10:48

Why do you specify #define STB_IMAGE_IMPLEMENTATION when using the stb_image library?

Why is it used #define STB_IMAGE_IMPLEMENTATIONwhen the code in the file loads an image?

implementation file where indicated

#include "Image.h"


#include <memory>
#include <stdexcept>

#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>

Image Image::loadFromFile(const std::string& path)
{
  int x, y, channels;

  std::unique_ptr<stbi_uc> data = std::unique_ptr<stbi_uc>(stbi_load(("res/texture/" + path).c_str(), &x, &y, &channels, 0));
  if (data == nullptr)
  {
    throw std::runtime_error("could not load image: " + path);
  }
  Format format;

  switch (channels)
  {
  case 3:
    format = RGB;
    break;
    
  case 4:
    format = RGBA;
    break;

  default:
    throw std::runtime_error("invalid channel count (" + std::to_string(channels) + ") in file: " + path);
  }

  int size = x * y * channels;
  return Image(x, y, std::vector<char>{data.get(), data.get() + size}, format);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2021-07-13
@IliaNeverov

Libraries usually use a similar approach, where the same header file is used when compiling the library itself and when compiling user applications that use the library (your case).
For example, for a Microsoft compiler, to declare exported functions (when compiling a library), one attribute is required for the function, and another attribute is required to import it from the library (when compiling an application). These are the things that are regulated by this macro.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question