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

使用libpqxx时出现Undefined symbols链接错误求助

解决macOS Sequoia上libpqxx链接错误(Undefined symbols for arm64)

问题详情

系统:macOS Sequoia 15.3.1
程序代码:

#include <pqxx/pqxx>
int main()
{
    pqxx::connection connection(""); 
    return 0;
}

编译命令(存在笔误):

g++ -std=c++23 -arch arm64 x.cc -lpqxx -lpq -I/usr/local/include -L/usr/local/libc-L/opt/homebrew/opt/libpq/lib -I/opt/homebrew/opt/libpq/include

已尝试的解决方法:

  • 通过brew install libpqxx安装并手动指定头文件/库路径
  • 手动在/usr/local/下编译构建libpqxx
  • 使用CMake的三种方式:fetch_content、pkg-config、配合Homebrew版本

始终出现链接错误:

Undefined symbols for architecture arm64:
  "pqxx::argument_error::argument_error(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&)", referenced from:
      pqxx::internal::(anonymous namespace)::throw_for_encoding_error(char const*, char const*, unsigned long, unsigned long) in ccBebBm9.o
  "pqxx::internal::demangle_type_name[abi:cxx11](char const*)", referenced from:
      __static_initialization_and_destruction_0() in ccBebBm9.o
      __static_initialization_and_destruction_0() in ccBebBm9.o
      __static_initialization_and_destruction_0() in ccBebBm9.o
      __static_initialization_and_destruction_0() in ccBebBm9.o
ld: symbol(s) not found for architecture arm64
collect2: error: ld returned 1 exit status

错误分析

该错误属于链接阶段的符号缺失问题,核心原因通常是:

  1. 编译命令存在语法错误,导致库路径未被正确识别
  2. 自定义代码与libpqxx库的C++标准/ABI(应用二进制接口)不匹配
  3. 库文件的架构与目标架构(arm64)不兼容
  4. 链接时库的顺序不正确,导致链接器无法找到依赖符号

解决方案

1. 修复编译命令的笔误

原命令中-L/usr/local/libc-L/opt/homebrew/opt/libpq/lib是明显的输入错误,应拆分为两个独立的库路径参数,同时调整参数顺序(链接器从左到右解析依赖,源文件需放在库参数前):

g++ -std=c++17 -arch arm64 x.cc -I/usr/local/include -I/opt/homebrew/opt/libpq/include -L/usr/local/lib -L/opt/homebrew/opt/libpq/lib -lpqxx -lpq

2. 验证库文件的架构兼容性

检查libpqxx和libpq是否支持arm64架构:

# 检查libpqxx架构
lipo -info /usr/local/lib/libpqxx.dylib
# 检查libpq架构
lipo -info /opt/homebrew/opt/libpq/lib/libpq.dylib

输出需包含arm64,否则说明库是为其他架构编译的,需要重新安装或编译对应版本。

3. 统一C++标准与ABI

libpqxx默认可能以C17标准编译,而-std=c++23可能触发ABI差异。尝试将编译标准降至C17或C++20,同时用pkg-config自动获取正确参数,避免手动指定路径出错:

g++ -std=c++17 -arch arm64 x.cc $(pkg-config --cflags --libs libpqxx)

4. 重新编译libpqxx(针对手动编译场景)

如果上述方法无效,从源码重新编译libpqxx,明确指定架构和C++标准:

git clone https://github.com/jtv/libpqxx.git
cd libpqxx
mkdir build && cd build
# 指定arm64架构、C++17标准及安装路径
cmake -DCMAKE_CXX_STANDARD=17 -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_INSTALL_PREFIX=/usr/local ..
make && sudo make install

编译完成后,再用修复后的命令编译你的代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 03:58:15