首页 > 解决方案 > 我应该如何使用 stb_image 标头构建一个 emscripten 项目?

问题描述

我有一个 webassembly 项目,我想用 emscripten 构建它。

我在我的项目中克隆了stbi 图像头文件,然后尝试编译所有内容。

我的main.c样子是这样的:

#include "stb_image.h"
#include <emscripten.h>

...

EMSCRIPTEN_KEEPALIVE
void my_func(int test) {
    // I need some functions from stbi image
    stbi_load_from_memory(...)
};

所以我尝试的第一件事是emcc main.c

我收到第一个错误:

error: undefined symbol: stbi_write_jpg_to_func (referenced by top-level compiled C/C++ code)
warning: Link with `-s LLD_REPORT_UNDEFINED` to get more information on undefined symbols
warning: To disable errors for undefined symbols use `-s ERROR_ON_UNDEFINED_SYMBOLS=0`
warning: _stbi_write_jpg_to_func may need to be added to EXPORTED_FUNCTIONS if it arrives from a system library
Error: Aborting compilation due to previous errors

然后我尝试先编译库,如文档中所述

第一个命令emcc stb_image.h main.c -c,我收到警告。

clang-11: warning: treating 'c-header' input as 'c++-header' when in C++ mode, this behavior is deprecated [-Wdeprecated]

当我尝试使用它的结果时,它总是失败。


如果我反过来做:emcc main.c stb_image.h -c这次我得到一个错误:

emcc: error: cannot mix precompile headers with non-header inputs: ['main.c', 'stb_image.h'] : main.c

所以我不知道我能做些什么来正确编译它。

我对 gcc、linking 和 emcc 不太了解:

我的 makefile 必须如何构建它?

甚至可能吗?

标签: clinkerheaderemscripten

解决方案


您需要STB_IMAGE_IMPLEMENTATION在包含标题之前进行定义,如下所示:

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

与大多数库不同,STB 头文件(通常)直接在项目的源代码中编译;无需链接。
大多数其他 stb 标头要求您在包含它们之前定义特殊宏。阅读文档(在头文件的顶部)以了解要定义的宏。


推荐阅读