parent
ecc5464024
commit
c48be3a742
|
@ -7057,6 +7057,61 @@ const c = @cImport({
|
|||
});
|
||||
{#code_end#}
|
||||
{#see_also|@cImport|@cInclude|@cDefine|@cUndef|@import#}
|
||||
{#header_close#}
|
||||
{#header_open|Exporting a C Library#}
|
||||
<p>
|
||||
One of the primary use cases for Zig is exporting a library with the C ABI for other programming languages
|
||||
to call into. The <code>export</code> keyword in front of functions, variables, and types causes them to
|
||||
be part of the library API:
|
||||
</p>
|
||||
<p class="file">mathtest.zig</p>
|
||||
{#code_begin|syntax#}
|
||||
export fn add(a: i32, b: i32) i32 {
|
||||
return a + b;
|
||||
}
|
||||
{#code_end#}
|
||||
<p>To make a shared library:</p>
|
||||
<pre><code class="shell">$ zig build-lib mathtest.zig
|
||||
</code></pre>
|
||||
<p>To make a static library:</p>
|
||||
<pre><code class="shell">$ zig build-lib mathtest.zig --static
|
||||
</code></pre>
|
||||
<p>Here is an example with the {#link|Zig Build System#}:</p>
|
||||
<p class="file">test.c</p>
|
||||
<pre><code class="cpp">// 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;
|
||||
}</code></pre>
|
||||
<p class="file">build.zig</p>
|
||||
{#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#}
|
||||
<p class="file">terminal</p>
|
||||
<pre><code class="shell">$ zig build
|
||||
$ ./test
|
||||
$ echo $?
|
||||
0</code></pre>
|
||||
{#header_close#}
|
||||
{#header_open|Mixing Object Files#}
|
||||
<p>
|
||||
|
|
Loading…
Reference in New Issue