How to link to a static library?

Zig Folk,

My next goal is to link a linux static library into some zig code that I am writing. (This is a fft library libfftw3.a compiled on linux from the fftw source code).

I have found some hints that it should be possible to link zig programs with linux (non-zig generated) static libraries … but do not have a clear picture on this.

Is this possible at present? Could someone point me to some information? (Examples of source in my .zig files and any needed command line arguments would be excellent.)

Thanks in advance for any and all advice!

Cheers,
AB

1 Like

I don’t know how to link a compiled static library, but I know how to build and link a static library from source:

const janet = b.addStaticLibrary("janet", null);
janet.addCSourceFile("libpath/c/janet.c", &[_][]const u8{"-std=c99"});
janet.addIncludeDir("libpath/c");
janet.linkLibC();

and later on your exe

exe.linkLibC();
exe.linkLibrary(janet);
exe.addPackagePath("jzignet", "libpath/src/janet.zig");
exe.addIncludeDir("libpath/c");

I suppose that you need to find a replacement for addCSourceFile so that you could include an already built artifact, or maybe you could specify a path to this library as a second argument to addStaticLibrary whereas here it’s null.

Greenfork, Thank you for your reply and information.

While it is not immediately clear to me how to proceed, the posting gives me some possible paths to follow. I now understand a few search terms to dig through the zig source tree. Much appreciated!

Time for me to do some digging and hacking! I will try.

Cheers,
AB

1 Like

Static libraries are typically just containers for object files, so you only need to add something like this in your build.zig file:

exe.addObjectFile("lib/mystaticlib.a");

EDIT: in fact @ikskuh’s latest tutorial on zig build just dropped, and it provides an answer to this same question :slight_smile: See: zig build explained - part 3 - Zig NEWS

1 Like

Thanks jmc — I am reading through Felix’s “zig build explained” series right now. It does an excellent job of describing many aspects of build (that I had been completely unaware of).

Learning this feels like a big forward step for me and zig. Mucho gracias!