You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WSL环境下C++编译集成TensorFlow Lite的问题求助

最简TensorFlow Lite C++推理CMake配置与实现

修正后的CMakeLists.txt

原配置因引入整个TFLite源码树(包含benchmark等依赖TSL的非核心模块)导致编译错误,以下配置仅编译TFLite核心推理库,避免不必要的依赖:

project(inference)
cmake_minimum_required(VERSION 3.16) # TFLite官方推荐最低版本

# 指定TensorFlow源码根目录
set(TENSORFLOW_SOURCE_DIR "../tensorflow_src" CACHE PATH "TensorFlow源码根目录")

# 仅编译TFLite核心推理库,排除benchmark、工具链等非必要模块
add_subdirectory(
    "${TENSORFLOW_SOURCE_DIR}/tensorflow/lite/core"
    "${CMAKE_CURRENT_BINARY_DIR}/tensorflow-lite-core" EXCLUDE_FROM_ALL
)

# 生成可执行文件
add_executable(inference inference.cpp model.cc)

# 链接TFLite核心库及系统依赖
target_link_libraries(inference
    tensorflow-lite-core
    pthread
    m
)

# 指定C++标准
target_compile_features(inference PRIVATE cxx_std_17)

核心推理代码示例(inference.cpp)

以下是最简实例化解释器、加载模型并执行推理的代码:

#include <tensorflow/lite/interpreter.h>
#include <tensorflow/lite/kernels/register.h>
#include <tensorflow/lite/model.h>
#include <cstdio>
#include <vector>

// 假设model.cc中导出了模型二进制数组
extern const unsigned char model_data[];
extern const int model_data_size;

int main() {
    // 从内存加载模型
    std::unique_ptr<tflite::FlatBufferModel> model =
        tflite::FlatBufferModel::BuildFromBuffer(
            reinterpret_cast<const char*>(model_data), model_data_size);
    
    if (!model) {
        fprintf(stderr, "模型加载失败\n");
        return 1;
    }

    // 创建解释器构建器
    tflite::ops::builtin::BuiltinOpResolver resolver;
    std::unique_ptr<tflite::Interpreter> interpreter;
    tflite::InterpreterBuilder(*model, resolver)(&interpreter);

    if (!interpreter) {
        fprintf(stderr, "解释器创建失败\n");
        return 1;
    }

    // 分配张量内存
    if (interpreter->AllocateTensors() != kTfLiteOk) {
        fprintf(stderr, "张量内存分配失败\n");
        return 1;
    }

    // 填充输入数据(示例:假设输入为1x3的浮点数组)
    float* input = interpreter->typed_input_tensor<float>(0);
    input[0] = 1.0f;
    input[1] = 2.0f;
    input[2] = 3.0f;

    // 执行推理
    if (interpreter->Invoke() != kTfLiteOk) {
        fprintf(stderr, "推理执行失败\n");
        return 1;
    }

    // 获取并打印输出结果
    float* output = interpreter->typed_output_tensor<float>(0);
    printf("推理输出:%.2f\n", output[0]);

    return 0;
}

编译步骤

  1. 确保TensorFlow源码子模块完整拉取:
cd ../tensorflow_src
git submodule update --init --recursive
  1. 进入build目录编译:
cd build
cmake ..
make -j$(nproc)

错误排查

  • 若仍出现TSL文件找不到:确认tensorflow_src的子模块已拉取完整,或改用TFLite预编译库替代源码编译。
  • 若出现链接错误:检查是否缺少系统依赖(如pthread、m),在target_link_libraries中补充对应库。

内容的提问来源于stack exchange,提问作者Luca Stefanescu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 02:20:55