authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-08-27 17:44:58-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-08-27 17:44:58-04:00
logc48be3a742cd82a8007512bfe145374e4b3750be
tree208a195d1ace69ad2e3be76893b26ffa4234275b
parentecc54640243ba84ffa3656b73aa7dd6b53474462
signaturelock-open Commit is signed but in an unrecognized format.

langref: document exporting a library

closes #1431

1 files changed, 55 insertions(+), 0 deletions(-)

doc/langref.html.in+55
......@@ -7057,6 +7057,61 @@ const c = @cImport({
70577057});
70587058 {#code_end#}
70597059 {#see_also|@cImport|@cInclude|@cDefine|@cUndef|@import#}
7060 {#header_close#}
7061 {#header_open|Exporting a C Library#}
7062 <p>
7063 One of the primary use cases for Zig is exporting a library with the C ABI for other programming languages
7064 to call into. The <code>export</code> keyword in front of functions, variables, and types causes them to
7065 be part of the library API:
7066 </p>
7067 <p class="file">mathtest.zig</p>
7068 {#code_begin|syntax#}
7069export fn add(a: i32, b: i32) i32 {
7070 return a + b;
7071}
7072 {#code_end#}
7073 <p>To make a shared library:</p>
7074 <pre><code class="shell">$ zig build-lib mathtest.zig
7075</code></pre>
7076 <p>To make a static library:</p>
7077 <pre><code class="shell">$ zig build-lib mathtest.zig --static
7078</code></pre>
7079 <p>Here is an example with the {#link|Zig Build System#}:</p>
7080 <p class="file">test.c</p>
7081 <pre><code class="cpp">// This header is generated by zig from mathtest.zig
7082#include "mathtest.h"
7083#include &lt;assert.h&gt;
7084
7085int main(int argc, char **argv) {
7086 assert(add(42, 1337) == 1379);
7087 return 0;
7088}</code></pre>
7089 <p class="file">build.zig</p>
7090 {#code_begin|syntax#}
7091const Builder = @import("std").build.Builder;
7092
7093pub fn build(b: *Builder) void {
7094 const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0));
7095
7096 const exe = b.addCExecutable("test");
7097 exe.addCompileFlags([][]const u8{"-std=c99"});
7098 exe.addSourceFile("test.c");
7099 exe.linkLibrary(lib);
7100
7101 b.default_step.dependOn(&exe.step);
7102
7103 const run_cmd = b.addCommand(".", b.env_map, [][]const u8{exe.getOutputPath()});
7104 run_cmd.step.dependOn(&exe.step);
7105
7106 const test_step = b.step("test", "Test the program");
7107 test_step.dependOn(&run_cmd.step);
7108}
7109 {#code_end#}
7110 <p class="file">terminal</p>
7111 <pre><code class="shell">$ zig build
7112$ ./test
7113$ echo $?
71140</code></pre>
70607115 {#header_close#}
70617116 {#header_open|Mixing Object Files#}
70627117 <p>