我应该如何使用 stb_image headers 构建 emscripten 项目?

How am I supposed to build an emscripten project with the stb_image headers?

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

我在我的项目中克隆了 stbi image header files,然后尝试编译所有内容。

我的 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

然后我尝试先编译库,如the docs

中所述

第一个命令 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、链接和 emcc:

我的 makefile 必须是什么样子才能构建它?

有可能吗?

您需要在包含 header 之前定义 STB_IMAGE_IMPLEMENTATION,如下所示:

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

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