C++中正确链接nlopt库的方法及架构不兼容问题求助
解决ARM64 macOS下nlopt库链接失败的问题
问题现象
编译C++代码时出现如下链接错误:
ld: warning: ignoring file '/usr/local/Cellar/nlopt/2.9.1/lib/libnlopt.0.13.0.dylib': found architecture 'x86_64', required architecture 'arm64' Undefined symbols for architecture arm64: "_nlopt_create", referenced from: nlopt::opt::opt(nlopt::algorithm, unsigned int) in nlopt_test-cc0bb7.o
编译命令:
g++ -std=c++14 -I /usr/local/include nlopt_test.cpp -o nlopt_test -L /usr/local/lib -lnlopt
测试代码:
#include <nlopt.hpp> int main() { // Create an optimizer object nlopt::opt opt(nlopt::LN_COBYLA, 2); // Do stuff }
原因分析
通过file /usr/local/lib/libnlopt.0.13.0.dylib确认,brew安装的nlopt库为x86_64架构,但当前编译目标是ARM64(Apple Silicon)架构,链接器会忽略架构不匹配的库,最终导致符号未定义错误。
解决方案
方案1:源码编译ARM64版本的nlopt
- 卸载现有x86_64版本的nlopt:
brew uninstall nlopt - 下载源码并编译适配ARM64:
git clone https://github.com/stevengj/nlopt.git cd nlopt mkdir build && cd build # 指定编译架构为ARM64,安装到系统默认路径 cmake .. -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_INSTALL_PREFIX=/usr/local make && sudo make install - 重新执行原编译命令即可正常链接。
方案2:强制编译为x86_64架构(依赖Rosetta)
修改编译命令,添加-arch x86_64参数,让编译产物适配x86_64架构,通过Rosetta兼容现有库:
g++ -std=c++14 -arch x86_64 -I /usr/local/include nlopt_test.cpp -o nlopt_test -L /usr/local/lib -lnlopt
方案3:使用ARM64版本的brew安装nlopt
如果系统同时存在x86_64(/usr/local)和ARM64(/opt/homebrew)版本的brew:
- 用ARM64 brew安装适配架构的nlopt:
/opt/homebrew/bin/brew install nlopt - 编译时指定ARM64版本的库路径:
g++ -std=c++14 -I /opt/homebrew/include nlopt_test.cpp -o nlopt_test -L /opt/homebrew/lib -lnlopt
内容的提问来源于stack exchange,提问作者user29235041
相关产品推荐
相关产品推荐

