Search code examples
cmakemeson-build

How can I specify library path when using Meson?


I'm trying to build a c++ project with Meson.

The thing is, I have some libraries under /opt/conda but can't figure out how to link the project when running meson build. It seems to be only searching through /usr/lib directory.

As far as I understood, meson uses cmake and pkg-config to look for libraries. Then would setting something like CMAKE_PREFIX_PATH be a feasible solution? and if so, how can I do that?

Thanks in advance.


Solution

  • I see two possible approaches to solve your problem.

    • the first solution uses LIBRARY_PATH, which is different from LD_LIBRARY_PATH as explained later.
    • the second solution uses a modified meson file to directly pass options to the linker. Optionally, it also uses rpath that eliminates the need to modify LD_LIBRARY_PATH afterward.

      1. First solution

    When building your project the linker use LIBRARY_PATH (and not LD_LIBRARY_PATH)

    LIBRARY_PATH is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.

    LD_LIBRARY_PATH is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.

    further details: LD_LIBRARY_PATH vs LIBRARY_PATH

    Maybe you can try

    export LIBRARY_PATH=/opt/conda/:$LIBRARY_PATH
    

    before running meson to build your project.

    1. Second solution

    Modifying your meson file and use rpath (optional)

    An alternative to the previous first solution is to directly modify your Meson file to pass some options to the linker.

    Here is something I used in the past you can easily adapt to your problem:

    #
    # blaspp
    #
    blaspp_lib = 'blaspp'
    blaspp_lib_dir = '/opt/slate/lib'
    blaspp_header_dir = '/opt/slate/include'
    
    blaspp_dep = declare_dependency(
        link_args : ['-L' + blaspp_lib_dir, '-l' + blaspp_lib],
        include_directories : include_directories(blaspp_header_dir))
    
    executable('test_blaspp',
           'test_blaspp.cpp',
           build_rpath : blaspp_lib_dir,
           install_rpath : blaspp_lib_dir,
           dependencies : [blaspp_dep])
    
    • declare_dependency(...) defines options to pass to the linker (this replaces the need to define LIBRARY_PATH in the first solution)

    • executable(...) defines rpath. This is an optional step that embeds the extra library path information directly into the executable. If you use this, you will not have to modify the LD_LIBRARY_PATH when running your executable.

    Further details: https://amir.rachum.com/blog/2016/09/17/shared-libraries/ (have a look at the "rpath and runpath" section) and see wikipedia: https://en.wikipedia.org/wiki/Rpath