当 运行 "cargo build" 时,我应该如何解决 "ld: library not found for -liconv" 错误?

How should I resolve a "ld: library not found for -liconv" error when running "cargo build"?

通过以下命令安装 Rust 和 Cargo 后...

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

我 运行 cargo build 在一个很小的“Hello World” Rust 项目上遇到了以下错误:

= note: ld: library not found for -liconv
          collect2: error: ld returned 1 exit status
          

error: could not compile `hello_world` due to previous error

我已经尝试 rustup self uninstall 然后通过 brew 安装 Rust 和 Cargo,但是在尝试构建时我遇到了同样的错误。

我是 运行 macOS Big Sur 11.6.4。

第一步是通过 Homebrew 安装 libiconv

brew install libiconv

注意输出中有些奇怪的东西:

==> Caveats
libiconv is keg-only, which means it was not symlinked into /opt/homebrew,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have libiconv first in your PATH, run:
  echo 'export PATH="/opt/homebrew/opt/libiconv/bin:$PATH"' >> ~/.zshrc

For compilers to find libiconv you may need to set:
  export LDFLAGS="-L/opt/homebrew/opt/libiconv/lib"
  export CPPFLAGS="-I/opt/homebrew/opt/libiconv/include"

我无法拼凑出完整的解释,但这与 MacOS 提供的 libiconv 版本符号错误有关。在我的系统上找不到libiconv(是不是M1的东西?);尽管如此,brew 拒绝踩操作系统的脚趾,这似乎是一个合理的决定。

但是这些变量不适用于 cargo

解决问题(我发现)的最佳方法是修改 LIBRARY_PATH 变量以提供 iconv 的路径。您可能已经不得不修改 LIBRARY_PATH(参见 https://apple.stackexchange.com/questions/40704/homebrew-installed-libraries-how-do-i-use-them)。

我所做的是将以下行添加到我的 ~/.zshrc:

export LIBRARY_PATH=$LIBRARY_PATH:$(brew --prefix)/lib:$(brew --prefix)/opt/libiconv/lib

之后 libiconv 检测正确。