Cxxdroid 中文文档 下载 App

SDL_image 找不到怎么修 —— SDL_image.so / SDL2_image 链接错误

典型报错

编译或运行 SDL_image 相关代码时可能遇到:

编译错误:
CMake Error: Could NOT find SDL2_image (missing: SDL2_IMAGE_LIBRARY SDL2_IMAGE_INCLUDE_DIR)

链接错误:
undefined reference to `IMG_Load'
undefined reference to `IMG_Init'

运行错误:
dlopen failed: library "libSDL2_image.so" not found

原因 1:SDL_image 没装

最直接的原因。包管理器搜索「SDL_image」或「sdl2-image」,点击安装。

装完需要 CMake 重新配置(清理 build 目录后重新编译,或手动触发 CMake 配置)。

原因 2:find_package 找不到

部分 Cxxdroid 版本的 SDL_image 预构建可能没有正确注册 CMake 的 FindSDL2_image 模块。此时 find_package(SDL2_image REQUIRED) 会报找不到。

手动指定路径的方案:

# 手动指定 SDL_image 的路径(根据你实际安装的位置调整)
set(SDL2_IMAGE_DIR "/data/data/ru.iiec.cxxdroid/files/libs/SDL2_image")

add_library(SDL2_image STATIC IMPORTED)
set_target_properties(SDL2_image PROPERTIES
    IMPORTED_LOCATION "${SDL2_IMAGE_DIR}/lib/libSDL2_image.a"
    INTERFACE_INCLUDE_DIRECTORIES "${SDL2_IMAGE_DIR}/include"
)

target_link_libraries(mygame PRIVATE SDL2::SDL2 SDL2_image)

上面的路径只是示意——实际路径取决于你的 Cxxdroid 版本。可以用文件管理器进入 Cxxdroid 内部存储,找一下 libSDL2_image.a 的位置。

原因 3:SDL2_image vs SDL_image

注意名字差异:

代码里 include 时注意版本:

// SDL2_image 2.x
#include <SDL2_image/SDL_image.h>

// 或者有些版本直接是
#include <SDL_image.h>

CMake 里 find_package 的名字:

原因 4:运行时找不到 .so

如果编译通过但运行时报 dlopen failed: library "libSDL2_image.so" not found,说明:

解决方案:确保 CMake 链接的是静态版本 .a,而不是动态版本 .so。在 Cxxdroid 预构建的库里,通常默认提供静态链接。

原因 5:SDL 和 SDL_image 版本不匹配

SDL_image 有它依赖的 SDL 版本。如果你装了旧版 SDL_image 但新版 SDL,或者反过来,会出现链接错误。

解决方案:

  1. 包管理器里卸载 SDL 和 SDL_image
  2. 先装 SDL,再装 SDL_image
  3. 或者一起更新到最新版本

原因 6:Cxxdroid 版本过旧

极旧版本的 Cxxdroid(比如 5.0 之前)可能还没有 SDL_image 的预构建。升级到最新版试试。

快速验证

如果你想快速测试 SDL_image 是否工作,编译这个最小示例:

#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>

int main() {
    if (IMG_Init(IMG_INIT_PNG) == 0) return 1;

    // 随便一张 PNG
    SDL_Surface *surf = IMG_Load("/sdcard/Download/test.png");
    if (!surf) {
        IMG_Quit();
        return 2;
    }
    SDL_FreeSurface(surf);
    IMG_Quit();
    return 0;
}

编译运行返回 0 就是 SDL_image 没问题;返回非 0 说明有问题,按上面的原因逐一排查。