Library paths search priority

The library paths added with addLibraryPath function or --search-prefix option are priority when the zig build system search for libraries?

Why do you ask?

If a library fails to get found you can see the searched paths in the error:

// build.zig
exe_mod.addLibraryPath(b.path("extern"));
exe_mod.linkSystemLibrary("hello", .{});
zig build ->

  error: error: unable to find dynamic system library 'hello' using strategy 'paths_first'. searched paths:
    /home/tsdtas/scratchpad/extern/libhello.so // the addLibraryPath path
    /home/tsdtas/scratchpad/extern/libhello.a  // the addLibraryPath path
    /usr/local/lib/libhello.so
    /usr/local/lib/libhello.a
    /usr/lib/x86_64-linux-gnu/libhello.so
    /usr/lib/x86_64-linux-gnu/libhello.a
    /lib64/libhello.so
    /lib64/libhello.a
    /lib/libhello.so
    /lib/libhello.a
    /usr/lib64/libhello.so
    /usr/lib64/libhello.a
    /usr/lib/libhello.so
    /usr/lib/libhello.a
    /lib/x86_64-linux-gnu/libhello.so
    /lib/x86_64-linux-gnu/libhello.a

This makes me think addLibraryPath takes priority.

However, if you need to make sure your build uses a specific version of a library, it’s probably better to set up your build to cross compile, but target your native platform. This can be done with b.standardTargetOptions in build.zig or by using -Dtarget=<target triple>.

If you do that, then Zig will only search the paths you provide:

zig build -Dtarget=x86_64-linux-gnu ->

  error: error: unable to find dynamic system library 'hello' using strategy 'paths_first'. searched paths:
    /home/tsdtas/scratchpad/extern/libhello.so // the addLibraryPath path
    /home/tsdtas/scratchpad/extern/libhello.a  // the addLibraryPath path
1 Like