【问题标题】:Double inclusion and headers only library stbi_image双重包含和仅标题库 stbi_image
【发布时间】:2017-04-11 14:26:58
【问题描述】:

我有一个 main.cpp,包括 a.h(它有自己的 a.cpp) a.h 包括仅标头库“stbi_image.h”:

#ifndef STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#endif

(https://github.com/nothings/stb)

*.cpp 通过使用#pragma once 包含自己的*.h

但我仍然得到:

LNK1169 发现一个或多个多重定义符号 LNK2005 stb-failure 原因已经在 a.obj 文件中定义 = main.obj ... 和一堆 其他

这对我来说似乎是正确的,但正如我在这个问题中所理解的那样: Multiple definition and header-only libraries

也许我应该在我需要的 stb_image.h 函数中添加内联/静态? 我做错了吗?

提前致谢

【问题讨论】:

  • 您是否注意到stb_image.h 顶部附近的文档。据我了解:您应该在a.cpp 中包含stb_image.h 和pre-#define STB_IMAGE_IMPLEMENTATIONmain.cpp(以及其他任何地方)而不包含。 (这可能会允许定义只完成一次,否则您可以获得您现在实际遇到的链接问题。)
  • 上面的评论对我有用,这应该被接受为答案。

标签: c++ c++11 header inclusion header-only


【解决方案1】:
  1. 也许我应该将 inline/static 添加到我需要的 stb_image.h 函数中?

不,您已经有办法将“stb_image 函数”声明为静态或外部:

#define STB_IMAGE_STATIC
  1. 我做错了吗? 是的,你编译 'stb_image' 两次,每次包含 'stb_image.h' 所以,整个设计可以是:

Image.h:

#ifndef _IMAGE_H_
#define _IMAGE_H_

Class Image.h {
public:
    Image() : _imgData(NULL) {}
    virtual ~Image();
    ...
    void loadf(...);
    ...

    unsigned char* getData() const { return _imgData; }
protected:
    unsigned char* _imgData;
};
#endif

Image.cpp:

#include "Image.h"

#define STB_IMAGE_IMPLEMENTATION   // use of stb functions once and for all
#include "stb_image.h"

Image::~Image()
{ 
    if ( _imgData ) 
        stbi_image_free(_imgData); 
}

void Image::load(...) {
    _imgData = stbi_load(...);
}

ma​​in.cpp

#include "Image.h" // as you see, main.cpp do not know anything about stb stuff

int main() {
    Image* img = new Image();  // this is my 'wrapper' to stb functions
    img->load(...);

    myTexture(img->getData(), ...);

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多