ulysses_rex
ulysses_rex

Reputation: 420

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

After installing Rust and Cargo via the following command...

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

I ran cargo build on a tiny "Hello World" Rust project and got the following error:

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

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

I've tried rustup self uninstall then installing Rust and Cargo via brew, but I get the same error when attempting to build.

I'm running macOS Big Sur 11.6.4.

Upvotes: 13

Views: 17464

Answers (2)

Jeff Hykin
Jeff Hykin

Reputation: 2627

If you've installed GNU gcc, or really any not-Apple C compiler it can cause this issue.

In addition to doing what the other answer recommends (brew install libiconv) also check and see if your cc command is Apple clang or a version of gcc. You can do this with which -a cc.

You can basically force cc to be the apple clang version by running:

export PATH="/usr/bin/:$PATH"

Then rust should work

Upvotes: 8

matejcik
matejcik

Reputation: 2072

First step is to install libiconv via Homebrew:

brew install libiconv

Notice that the output is saying something weird:

==> 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"

I haven't been able to piece together a complete explanation, but it is something to do with libiconv being provided by MacOS in a version that has the wrong symbols. On my system libiconv can't be found (is it a M1 thing?); nevertheless, brew refuses to step on the OSes' toes, which seems a reasonable decision.

These variables do not apply to cargo however.

The best way to solve the problem (that I found) is to modify your LIBRARY_PATH variable to provide path to iconv. You might have already had to modify your LIBRARY_PATH (see e.g. https://apple.stackexchange.com/questions/40704/homebrew-installed-libraries-how-do-i-use-them).

What I did was to add the following line to my ~/.zshrc:

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

Afterwards libiconv is detected correctly.

Upvotes: 16

Related Questions