| 1 | # Protobuf 类问题解决方法 |
| 2 | |
| 3 | ## 问题分析 |
| 4 | |
| 5 | protobuf 有关的报错,一般都是两个原因: |
| 6 | |
| 7 | 1. 需要的 pb 没安装/`FindProtobuf.cmake`不存在,最终 `find_package` 失败 |
| 8 | 2. 系统不止一套 pb,导致 bin/lib/include 三者不匹配 |
| 9 | |
| 10 | 如果你遇到了这些报错,都可以通过本文档解决: |
| 11 | |
| 12 | 1. Linux 编译 `caffe2ncnn` 时报 `Protobuf not found` |
| 13 | 2. 编译 `caffe2ncnn` 时报 protoc 和 protobuf.so 版本不匹配 |
| 14 | |
| 15 | ## (推荐)通用处理办法 |
| 16 | |
| 17 | 这个办法包治百病,**不管什么情况一定生效** |
| 18 | |
| 19 | 1. 编译下载 protobuf,以 3.20.0 版本为例 |
| 20 | |
| 21 | ```bash |
| 22 | $ wget https://github.com/protocolbuffers/protobuf/releases/download/v3.20.0/protobuf-cpp-3.20.0.tar.gz |
| 23 | $ tar xvf protobuf-cpp-3.20.0.tar.gz |
| 24 | $ cd protobuf-3.20.0/ |
| 25 | $ ./configure --prefix=/path/to/install |
| 26 | $ make && make install |
| 27 | ``` |
| 28 | 注意需要 `--prefix`,不要装到系统里。能遇到这些错,说明本来系统环境就有问题,再给系统环境装 lib 就更乱了。 |
| 29 | |
| 30 | 2. 修改 cmake |
| 31 | |
| 32 | 找到报错的 CMakeLists.txt,在 `find_package` 前插入 protobuf 路径。 |
| 33 | |
| 34 | ```bash |
| 35 | # 加入下面 1 行 |
| 36 | list(APPEND CMAKE_PREFIX_PATH "/path/to/install") |
| 37 | |
| 38 | find_package(Protobuf REQUIRED) |
| 39 | ... |
| 40 | ``` |
| 41 | |
| 42 | 3. 调整 cmake 选项 |
| 43 | |
| 44 | `cmake ..` 时,额外加入选项 `-DProtobuf_PROTOC_EXECUTABLE=/path/to/install/bin/protoc` |
| 45 | |
| 46 | ```bash |
| 47 | $ cd /path/to/ncnn/build |
| 48 | $ rm -rf CMakeCache |
| 49 | # 加入新选项 |
| 50 | $ cmake .. -DProtobuf_PROTOC_EXECUTABLE=/path/to/install/bin/protoc |
| 51 | $ ... |
| 52 | ``` |
| 53 | |
| 54 | ## (不推荐)自己改环境变量 |
| 55 | |
| 56 | ### 一、遇到 `Protobuf not found` |
| 57 | |
| 58 | 是因为 protobuf 未安装或环境变量未设置 |
| 59 | |
| 60 | 1. 安装 protobuf |
| 61 | |
| 62 | Ubuntu 系统尝试以下命令 |
| 63 | ```bash |
| 64 | $ sudo apt-get install libprotobuf-dev protobuf-compiler |
| 65 | ``` |
| 66 | |
| 67 | CentOS 尝试 |
| 68 | ```bash |
| 69 | $ sudo yum install protobuf-devel.x86_64 protobuf-compiler.x86_64 |
| 70 | ``` |
| 71 | |
| 72 | 2. 然后设置 C++ 环境 |
| 73 | |
| 74 | 在 LD_LIBRARY_PATH 增加参数 |
| 75 | |
| 76 | ```bash |
| 77 | $ export LD_LIBRARY_PATH=${YOUR_PROTOBUF_LIB_PATH}:$LD_LIBRARY_PATH |
| 78 | ``` |
| 79 | |
| 80 | ### 二、遇到 protoc 和 protobuf.so 版本不匹配 |
| 81 | |
| 82 | 1. 先看 protoc 需要的 so 版本号 |
| 83 | ```bash |
| 84 | $ ldd `whereis protoc| awk '{print $2}'` | grep libprotobuf.so |
| 85 | ``` |
| 86 | |
| 87 | 例如是 libprotobuf.so.10 |
| 88 | |
| 89 | 2. 然后搜这个文件所在的路径 |
| 90 | ```bash |
| 91 | $ cd / && find . -type f | grep libprotobuf.so.10 |
| 92 | ``` |
| 93 | |
| 94 | 假设在`/home/user/mydir` |
| 95 | |
| 96 | 3. 设置 protobuf.so 的搜索目录 |
| 97 | ```bash |
| 98 | $ export LD_LIBRARY_PATH=/home/user/mydir:$LD_LIBRARY_PATH |
| 99 | ``` |
| 100 | |
| 101 | ### 三、行走江湖必备 |
| 102 | 关于环境变量设置、工具和技巧,强烈建议学习下 https://missing.csail.mit.edu/ |