From c48be3a742cd82a8007512bfe145374e4b3750be Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 27 Aug 2018 17:44:58 -0400 Subject: [PATCH] langref: document exporting a library closes #1431 --- doc/langref.html.in | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/doc/langref.html.in b/doc/langref.html.in index 465f3c56a..495b19580 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -7057,6 +7057,61 @@ const c = @cImport({ }); {#code_end#} {#see_also|@cImport|@cInclude|@cDefine|@cUndef|@import#} + {#header_close#} + {#header_open|Exporting a C Library#} +

+ One of the primary use cases for Zig is exporting a library with the C ABI for other programming languages + to call into. The export keyword in front of functions, variables, and types causes them to + be part of the library API: +

+

mathtest.zig

+ {#code_begin|syntax#} +export fn add(a: i32, b: i32) i32 { + return a + b; +} + {#code_end#} +

To make a shared library:

+
$ zig build-lib mathtest.zig
+
+

To make a static library:

+
$ zig build-lib mathtest.zig --static
+
+

Here is an example with the {#link|Zig Build System#}:

+

test.c

+
// This header is generated by zig from mathtest.zig
+#include "mathtest.h"
+#include <assert.h>
+
+int main(int argc, char **argv) {
+    assert(add(42, 1337) == 1379);
+    return 0;
+}
+

build.zig

+ {#code_begin|syntax#} +const Builder = @import("std").build.Builder; + +pub fn build(b: *Builder) void { + const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0)); + + const exe = b.addCExecutable("test"); + exe.addCompileFlags([][]const u8{"-std=c99"}); + exe.addSourceFile("test.c"); + exe.linkLibrary(lib); + + b.default_step.dependOn(&exe.step); + + const run_cmd = b.addCommand(".", b.env_map, [][]const u8{exe.getOutputPath()}); + run_cmd.step.dependOn(&exe.step); + + const test_step = b.step("test", "Test the program"); + test_step.dependOn(&run_cmd.step); +} + {#code_end#} +

terminal

+
$ zig build
+$ ./test
+$ echo $?
+0
{#header_close#} {#header_open|Mixing Object Files#}