macOS下pecl安装Mosquitto-alpha因找不到cjson/cJSON.h失败求助
macOS下pecl安装Mosquitto-alpha因找不到cjson/cJSON.h失败求助
问题场景
我在运行Tahoe 26.2 (25C56)的MacStudio上尝试安装Mosquitto-alpha,目的是在PHP脚本中使用MQTT。PHP 8.5通过Homebrew安装且运行正常,Mosquitto 2.1.2也是通过Homebrew安装的,同样正常工作。
安装Mosquitto-alpha时出现了以下错误(不管在哪个目录执行,结果都一样):
@MiniServer Mosquitto-0.4.0 % pecl install Mosquitto-alpha downloading Mosquitto-0.4.0.tgz ... Starting to download Mosquitto-0.4.0.tgz (23,804 bytes) ........done: 23,804 bytes 5 source files, building running: phpize Configuring for: PHP Version: 8.5 PHP Api Version: 20250925 Zend Module Api No: 20250925 Zend Extension Api No: 420250925 Please provide the prefix of the libmosquitto installation [autodetect] : /opt/homebrew/opt/mosquitto building in /private/tmp/pear/temp/pear-build-peterwileyhvsdt26sus1uaOWn0O6/Mosquitto-0.4.0 running: /private/tmp/pear/temp/Mosquitto/configure --with-php-config=/opt/homebrew/opt/php/bin/php-config --with-mosquitto=/opt/homebrew/opt/mosquitto # 中间配置输出省略... In file included from /private/tmp/pear/temp/Mosquitto/mosquitto.c:12: In file included from /private/tmp/pear/temp/Mosquitto/php_mosquitto.h:37: In file included from /opt/homebrew/opt/mosquitto/include/mosquitto.h:30: In file included from /opt/homebrew/opt/mosquitto/include/mosquitto/libcommon.h:40: /opt/homebrew/opt/mosquitto/include/mosquitto/libcommon_cjson.h:31:10: fatal error: 'cjson/cJSON.h' file not found 31 | #include <cjson/cJSON.h> | ^~~~~~~~~~~~~~~ 1 error generated. make: *** [mosquitto.lo] Error 1 ERROR: `make' failed
根据brew info cjson的输出,cjson已经安装,我也尝试过重新安装它,但问题依旧。我怀疑是路径问题,但对文件系统/架构的理解有限,不知道具体哪里出了问题。
解决办法
核心问题是:Apple Silicon的Mac上,Homebrew软件默认安装在/opt/homebrew目录,这个路径不在系统默认的编译搜索路径中;而Mosquitto PHP扩展的编译脚本只自动识别了mosquitto的路径,没处理cjson的依赖路径。这里有几个简单的解决方法:
方法一:安装前设置环境变量指定cjson路径
先告诉编译系统cjson的头文件和库文件位置,再执行pecl安装:
# 指定cjson头文件路径 export CFLAGS="-I/opt/homebrew/opt/cjson/include" # 指定cjson库文件路径 export LDFLAGS="-L/opt/homebrew/opt/cjson/lib" # 继续执行安装,mosquitto前缀仍填写/opt/homebrew/opt/mosquitto pecl install Mosquitto-alpha
方法二:通过pkg-config让系统自动识别依赖
利用pkg-config工具帮编译系统自动找到cjson的配置:
# 先测试pkg-config是否能识别cjson pkg-config --cflags --libs cjson # 如果上面的命令报错,先添加cjson的pkg-config配置路径 export PKG_CONFIG_PATH="/opt/homebrew/opt/cjson/lib/pkgconfig:$PKG_CONFIG_PATH" # 再重新执行pecl安装 pecl install Mosquitto-alpha
方法三:手动编译扩展(进阶)
如果前两种方法都无效,可以手动下载源码,明确指定所有依赖的路径:
# 下载扩展源码包 pecl download Mosquitto-alpha # 解压源码 tar zxvf Mosquitto-0.4.0.tgz cd Mosquitto-0.4.0 # 初始化PHP扩展编译环境 phpize # 配置编译参数,同时指定mosquitto和cjson的路径 ./configure --with-php-config=/opt/homebrew/opt/php/bin/php-config --with-mosquitto=/opt/homebrew/opt/mosquitto --with-cjson=/opt/homebrew/opt/cjson # 编译并安装 make && make install
备注:内容来源于stack exchange,提问作者Peter Wiley
相关产品推荐
相关产品推荐

