c++macoscmakehomebrew

CMake cannot found libraries installed by brew


Idk why my previous topic was determined like 'question not related for programming and tools` but I'll ask again and more accurate.

I moved from Windows to Mac and started working on my C++ project.

I installed brew, configured it and started to install libraries that I need.

  1. I installed openldap lib.
  2. Openldap installation hint helped me to add path into my ~./zshrc environment:
export PKG_CONFIG_PATH="/opt/homebrew/opt/openldap/lib/pkgconfig"

After that CMake successfully detected ldap, but when I installed hiredis, I got an error that hiredis can't be found. Again. So, then I moved to ~/.zshrc again and add another path and my PKG_CONFIG_PATH starts look like:

  export PKG_CONFIG_PATH="/opt/homebrew/opt/openldap/lib/pkgconfig":"/opt/homebrew/opt/hiredis/lib/pkgconfig"

To be honest, it's awful. After any brew installation I should always add new library path to help CMake detect it? Or there is more simple way for it?


Solution

  • When installing packages, the homebrew package manager links files from the package-specific directory /opt/homebrew/Cellar/$PACKAGE/$VERSION/... into /opt/homebrew/{include,lib,share}.

    Packages that ship a pkg-config .pc file (such as hiredis) end up linked into /opt/homebrew/lib/pkgconfig. The homebrew-supplied pkg-config knows to find them there, and CMake's FindPkgConfig calls pkg-config to find these packages.

    However, some packages overlap system libraries / binaries and the Homebrew team does not do this automatic linking by default.

    Openldap is one such package:

    % brew info openldap
    ==> openldap: stable 2.6.9 (bottled) [keg-only]
    ...
    ==> Caveats
    openldap 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 openldap first in your PATH, run:
      echo 'export PATH="/opt/homebrew/opt/openldap/bin:$PATH"' >> ~/.zshrc
      echo 'export PATH="/opt/homebrew/opt/openldap/sbin:$PATH"' >> ~/.zshrc
    
    For compilers to find openldap you may need to set:
      export LDFLAGS="-L/opt/homebrew/opt/openldap/lib"
      export CPPFLAGS="-I/opt/homebrew/opt/openldap/include"
    
    For pkg-config to find openldap you may need to set:
      export PKG_CONFIG_PATH="/opt/homebrew/opt/openldap/lib/pkgconfig"
    

    For packages like these, you must explicitly tell pkg-config where to look. There are two options:

    1. set PKG_CONFIG_PATH before invoking CMake as above, or
    2. append /opt/homebrew to CMAKE_PREFIX_PATH. CMake will know to look under /opt/homebrew/lib/pkgconfig.