| ... | ... | @@ -7057,6 +7057,61 @@ const c = @cImport({ |
| 7057 | 7057 | }); |
| 7058 | 7058 | {#code_end#} |
| 7059 | 7059 | {#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#} |
| 7069 | export 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 | |
| 7085 | int 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#} |
| 7091 | const Builder = @import("std").build.Builder; |
| 7092 | |
| 7093 | pub 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 $? |
| 7114 | 0</code></pre> |
| 7060 | 7115 | {#header_close#} |
| 7061 | 7116 | {#header_open|Mixing Object Files#} |
| 7062 | 7117 | <p> |