.\" Made by website/plain/build.mjs from website/words/export.md; change that file. .TH SG-EXPORT 7 2026-11-28 "SG" "SG reference" .SH NAME export \- makes a function of SG that C calls by its name, or through a CFunc, a pointer to a function as C has it .SH SYNOPSIS .TP \fBexport R name(T a, U b) { ... }\fR a function at the top level that C calls by the name written .TP \fBCFunc\fR a pointer to a function as C calls it: the parameters, then what it gives .TP \fBCFunc f = name\fR the name of an export function, or of a function of C, as a CFunc .TP \fBunsafe f(a, b)\fR a call through a CFunc .TP \fB(raw void)f, unsafe (CFunc)p\fR the address as a raw void, and back .TP \fBexport Calc* make(), ref Calc, read Calc\fR in a library, a value of SG that C holds by its address .TP \fBsg build folder \-\-library\fR a static library of the export functions, and the header C includes .SH DESCRIPTION \fBexport\fR in front of a function at the top level makes it a function of C. C sees it under the name written, without its module, so the name is one in the whole program, is not a word of C, does not start as the names of the code SG writes do (\fBsg_\fR, \fBf_\fR and the like), and is not a function of C's library that the runtime uses (\fBstrlen\fR, \fBqsort\fR, \fBatoi\fR). It is not a method, not \fBasync\fR and not \fBmain\fR\&. .PP It takes and gives what C has: integers, \fBfloat\fR, \fBdouble\fR, \fBbool\fR, raw pointers, \fBCFunc\fR values and structs of plain data by value. A text from C is a \fBread CString\fR, its \fBconst char*\fR, which \fBstring.fromCString(text)\fR copies with no \fBunsafe\fR\&. A \fBstring\fR, a \fBchar\fR, a collection, a \fBT?\fR and a borrow of plain data are refused; a struct that owns memory goes by its address, as a library below shows. SG calls an \fBexport\fR function by its name with no \fBunsafe\fR, as any function; a C file of the program calls it by its name too, since SG declares it before the file. .PP C has no other way to call SG. \fBqsort\fR is given a comparator, a library of callbacks is given a function to call later, and the state a callback needs comes through C's \fBvoid*\fR: \fBunsafe Memory.addressOf(ref state)\fR gives the address, and inside the callback \fBunsafe (ref State)data\fR lends it again. The interpreter keeps the addresses it gave, and stops the program on a wrong type, a value that has ended or moved, and an address it did not give. Compiled code checks none of this. .PP A \fBCFunc\fR is written as a \fBFunc\fR is, with the types C has. It is plain data: it is copied, kept in a field and compared, and it may be \fBnull\fR as a pointer of C may, so \fBCFunc<...>?\fR is not written. Where one is expected, the name of an \fBexport\fR function or of a function of C is one. Each call through it is inside \fBunsafe\fR, since what it points at may be any function of C, and a call through a \fBnull\fR one stops the program. .PP A panic inside an \fBexport\fR function ends the process with its message: nothing unwinds through the frames of C between it and \fBmain\fR\&. A program with an \fBexport\fR function is built for several threads, so a thread C starts may call it. .PP \fBsg build folder \-\-library\fR builds a static library of a folder with no \fBmain\fR (\fB\-\-shared\fR a shared one), and writes the header C includes. Only the \fBexport\fR functions are seen from outside; each library carries its own runtime. A struct of SG that is not plain data goes to C by its address: an \fBexport\fR function gives it as \fBT*\fR, which C keeps, takes it back as \fBT*\fR, where it ends, or is lent it as \fBread T\fR or \fBref T\fR for the call. C sees only \fBtypedef struct Name Name;\fR, so it cannot reach inside. In a library a panic aborts the program, and so does a \fBNULL\fR given where no \fBnull\fR is taken. .SH EXAMPLES .SS "A comparator for qsort" .RS 4 .nf extern { void qsort(raw void base, nuint count, nuint size, CFunc compare) } struct Runner { int bib int seconds } // C calls this with the addresses of two items: fastest first, then by bib. export int fastestFirst(raw void a, raw void b) { var x = unsafe ((raw Runner)a)[0] var y = unsafe ((raw Runner)b)[0] if x.seconds != y.seconds { return x.seconds < y.seconds ? -1 : 1 } return x.bib < y.bib ? -1 : x.bib > y.bib ? 1 : 0 } void main() { var runners = List { Runner { bib = 7, seconds = 3121 }, Runner { bib = 3, seconds = 2990 }, Runner { bib = 12, seconds = 3121 }, Runner { bib = 1, seconds = 3305 }, } var size = (nuint)Memory.sizeOf() unsafe qsort((raw void)runners.pointer(), (nuint)runners.length(), size, fastestFirst) for r in runners { print($"{r.bib} {r.seconds}") } } .fi .RE .PP .RS 4 .nf 3 2990 7 3121 12 3121 1 3305 .fi .RE .PP \fBqsort\fR moves the items of the list in place and calls \fBfastestFirst\fR for each pair it compares. A \fBRunner\fR is plain data, laid out as C lays it out, so the comparator reads one through the address C gives. .SS "Called from SG, and kept as a CFunc" .RS 4 .nf extern { int abs(int value) } export int twice(int value) { return value * 2 } export int negate(int value) { return -value } struct Step { string name CFunc apply } void main() { print(twice(21)) var steps = List { Step { name = "twice", apply = twice }, Step { name = "negate", apply = negate }, Step { name = "abs", apply = abs }, Step { name = "none", apply = null }, } var value = 5 for step in steps { if step.apply == null { print($"{step.name}: skipped") continue } value = unsafe step.apply(value) print($"{step.name}: {value}") } CFunc f = twice var address = (raw void)f var back = unsafe (CFunc)address CFunc g = negate print(back == f) print(f == g) } .fi .RE .PP .RS 4 .nf 42 twice: 10 negate: -10 abs: 10 none: skipped true false .fi .RE .PP \fBtwice(21)\fR is an ordinary call. Through a \fBCFunc\fR the call is inside \fBunsafe\fR, whether it points at a function of SG or at \fBabs\fR of C, and a \fBnull\fR one is tested first. A \fBraw void\fR is how C hands a pointer to a function around (\fBdlsym\fR gives one); the cast back is inside \fBunsafe\fR, since nothing checks what lies there. .SS "A C file calls it by name" The file retry/retry.c: .PP .RS 4 .nf #include // Calls tryOnce, a function of SG, until it gives 0; the attempts it took, or -1. int32_t with_retries(int32_t limit) { for (int32_t attempt = 1; attempt <= limit; attempt++) { if (tryOnce(attempt) == 0) { return attempt; } } return -1; } .fi .RE .PP The file retry/main.sg: .PP .RS 4 .nf extern "./retry.c" { int with_retries(int limit) } export int tryOnce(int attempt) { print($"attempt {attempt}") return attempt < 3 ? 1 : 0 } void main() { print(unsafe with_retries(5)) print(unsafe with_retries(2)) } .fi .RE .PP .RS 4 .nf $ cd retry $ sg main.sg attempt 1 attempt 2 attempt 3 3 attempt 1 attempt 2 -1 $ sg build main.sg -o retry $ ./retry attempt 1 attempt 2 attempt 3 3 attempt 1 attempt 2 -1 .fi .RE .PP SG declares \fBint32_t tryOnce(int32_t)\fR before the C file, so the file calls it without a declaration of its own; one that differs (\fBint64_t tryOnce(int64_t)\fR) is an error of the C compiler. Calls go from SG to C and back again within one line of \fBmain\fR\&. .SS "State through C's void*" The file lines/lines.c: .PP .RS 4 .nf #include #include typedef void (*visit_fn)(void *start, uint64_t length, void *state); // Calls visit for each line of the text, without its '\en'. void each_line(const char *text, visit_fn visit, void *state) { const char *start = text; for (;;) { const char *end = strchr(start, '\en'); if (end == NULL) { if (*start != '\e0') visit((void *)start, strlen(start), state); return; } visit((void *)start, (uint64_t)(end - start), state); start = end + 1; } } .fi .RE .PP The file lines/main.sg: .PP .RS 4 .nf extern "./lines.c" { void each_line(read CString text, CFunc visit, raw void state) } struct Stats { int lines int blank nint longest } export void countLine(raw void start, nuint length, raw void data) { var stats = unsafe (ref Stats)data var bytes = unsafe (raw byte)start var line = unsafe Memory.view(bytes, (nint)length) stats.lines += 1 if line.length() == 0 { stats.blank += 1 } if line.length() > stats.longest { stats.longest = line.length() } } void main() { var poem = CString.from("The cat sat\en\enon the warm mat\enand slept") ?? panic("a zero byte inside") var stats = Stats { lines = 0, blank = 0, longest = 0 } unsafe each_line(read poem, countLine, Memory.addressOf(ref stats)) print($"{stats.lines} lines, {stats.blank} blank, the longest {stats.longest} bytes") } .fi .RE .PP .RS 4 .nf $ cd lines $ sg main.sg 4 lines, 1 blank, the longest 15 bytes $ sg build main.sg -o lines $ ./lines 4 lines, 1 blank, the longest 15 bytes .fi .RE .PP C knows nothing of \fBStats\fR: it carries its address as a \fBvoid*\fR and gives it back with each line. \fBcountLine\fR lends it again as \fBref Stats\fR, and reads the line where it lies through \fBMemory.view\fR, a \fBread byte[]\fR with the checks of a slice. The \fBCFunc\fR takes the parameter types the C file's \fBvisit_fn\fR has. .SS "A library for C" The file weather/temps/temps.sg: .PP .RS 4 .nf // Readings in tenths of a degree, kept by SG; C holds them by their address. struct Readings { List values } export Readings* temps_new() { return new Readings { values = List() } } export void temps_add(ref Readings r, int tenths) { r.values.add(tenths) } export void temps_add_all(ref Readings r, raw int items, nuint count) { for value in unsafe Memory.view(items, (nint)count) { r.values.add(value) } } // The mean, rounded down; 0 for none. export int temps_mean(read Readings r) { if r.values.length() == 0 { return 0 } long sum = 0 for v in read r.values { sum += v } return (int)(sum / r.values.length()) } export void temps_free(Readings* r) { } .fi .RE .PP The file weather/main.c: .PP .RS 4 .nf #include #include "temps.h" int main(void) { Readings *week = temps_new(); int32_t first[] = { 182, 175, 201 }; temps_add_all(week, first, 3); temps_add(week, 214); temps_add(week, -40); printf("mean %d\en", temps_mean(week)); temps_free(week); return 0; } .fi .RE .PP .RS 4 .nf $ cd weather $ sg build temps --library built libtemps.a and temps.h; a program links it with `libtemps.a -lm -pthread` $ cc -std=c11 -o weather main.c libtemps.a -lm -pthread $ ./weather mean 146 .fi .RE .PP \fBtemps.h\fR declares \fBtypedef struct Readings Readings;\fR and the five functions with the types of C (\fBint32_t\fR, \fBuint64_t\fR, \fBconst Readings *\fR for the \fBread\fR one), so C holds a \fBReadings\fR without seeing its list. \fBtemps_new\fR gives it to C; \fBtemps_free\fR takes it back, and it ends there, its list with it, at the end of the empty body. \fBtemps_add(NULL, 1)\fR would stop the program with \fBpanic: C gave `null` to `temps_add`, which takes a `ref Readings`\fR\&. .SH "WHAT STOPS THE PROGRAM" .SS "A panic inside a comparator" .RS 4 .nf extern { void qsort(raw void base, nuint count, nuint size, CFunc compare) } export int strictly(raw void a, raw void b) { var x = unsafe ((raw int)a)[0] var y = unsafe ((raw int)b)[0] if x == y { panic($"{x} is there twice") } return x < y ? -1 : 1 } void main() { var unique = List { 42, -7, 19, 3 } unsafe qsort((raw void)unique.pointer(), (nuint)unique.length(), 4, strictly) print(unique) var twice = List { 42, -7, 19, 42, 3 } unsafe qsort((raw void)twice.pointer(), (nuint)twice.length(), 4, strictly) print(twice) } .fi .RE .PP .RS 4 .nf [-7, 3, 19, 42] panic: 42 is there twice --> example.sg:9:9 9 | panic($"{x} is there twice") | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .fi .RE .PP \fBqsort\fR is in the middle, and C has no way to be left halfway, so the panic ends the process there, in the interpreter and in compiled code alike. An error a callback meets is kept in its state, and the caller looks at it when C returns. .SS "The address of another type" .RS 4 .nf struct Tally { int count } struct Other { long total } export void bump(raw void data) { var tally = unsafe (ref Tally)data tally.count += 1 } void main() { var right = Tally { count = 0 } CFunc f = bump unsafe f(Memory.addressOf(ref right)) print(right.count) var wrong = Other { total = 0 } unsafe f(Memory.addressOf(ref wrong)) print(wrong.total) } .fi .RE .PP .RS 4 .nf 1 panic: `(ref Tally)` is given the address of an `Other` --> example.sg:10:17 10 | var tally = unsafe (ref Tally)data | ^^^^^^^^^^^^^^^^^^^^^^ .fi .RE .PP The interpreter remembers the type behind each address \fBMemory.addressOf\fR gave. A compiled build does not: it writes the \fBint\fR into the first bytes of \fBwrong\fR and prints \fB1\fR, as a program of C would. .SS "A CFunc that is null" .RS 4 .nf struct Step { CFunc apply } void main() { var step = Step { apply = null } print(step.apply == null) print(unsafe step.apply(3)) } .fi .RE .PP .RS 4 .nf true panic: `apply` is called, and it is a `CFunc` that is `null` --> example.sg:8:11 8 | print(unsafe step.apply(3)) | ^^^^^^^^^^^^^^^^^^^^ .fi .RE .PP Compiled code tests the pointer before the call too, so a \fBnull\fR one stops the program with this message in every build. .SH "WHAT THE COMPILER REFUSES" .SS "A string from C" .RS 4 .nf export void greet(string name) { print(name) } void main() { greet("Ada") } .fi .RE .PP .RS 4 .nf error: C calls `greet`, and cannot give it a `string` --> example.sg:1:19 1 | export void greet(string name) { | ^^^^^^ hint: C gives a text as `read CString`, its `const char*`, which `string.fromCString(text)` copies .fi .RE .SS "A function of SG given to C" .RS 4 .nf extern { void qsort(raw void base, nuint count, nuint size, CFunc compare) } int byValue(raw void a, raw void b) { return 0 } void main() { var numbers = List { 3, 1, 2 } unsafe qsort((raw void)numbers.pointer(), (nuint)numbers.length(), 4, byValue) print(numbers) } .fi .RE .PP .RS 4 .nf error: C cannot call `byValue`: it is a function of SG --> example.sg:11:75 11 | unsafe qsort((raw void)numbers.pointer(), (nuint)numbers.length(), 4, byValue) | ^^^^^^^ hint: a function C calls is written with `export`: `export int byValue(...)` .fi .RE .SS "A comparator of the wrong type" .RS 4 .nf extern { void qsort(raw void base, nuint count, nuint size, CFunc compare) } export long byValue(raw void a, raw void b) { return 0 } void main() { var numbers = List { 3, 1, 2 } unsafe qsort((raw void)numbers.pointer(), (nuint)numbers.length(), 4, byValue) print(numbers) } .fi .RE .PP .RS 4 .nf error: expected `CFunc`, found `CFunc` --> example.sg:11:75 11 | unsafe qsort((raw void)numbers.pointer(), (nuint)numbers.length(), 4, byValue) | ^^^^^^^ .fi .RE .PP C would read half of the \fBlong\fR as the \fBint\fR it looks for. .SS "A call through a CFunc without unsafe" .RS 4 .nf export int twice(int value) { return value * 2 } void main() { CFunc f = twice print(f(4)) } .fi .RE .PP .RS 4 .nf error: `f` points at a function of C, and the checker cannot see what it does, so it is written inside `unsafe` --> example.sg:7:11 7 | print(f(4)) | ^^^^ hint: `unsafe f(4)`, or `unsafe { ... }` around several statements .fi .RE .PP \fBtwice(4)\fR needs no \fBunsafe\fR: by its name the compiler knows which function it is. .SS "A name of C's library" .RS 4 .nf export int strlen(raw byte text) { return 0 } void main() { print(strlen(null)) } .fi .RE .PP .RS 4 .nf error: C cannot see a function of SG named `strlen` `strlen` is a function of C's library or of the system, which the code SG writes uses --> example.sg:1:12 1 | export int strlen(raw byte text) { | ^^^^^^ .fi .RE .SS "A method" .RS 4 .nf struct Counter { int n export int bump(ref this) { this.n += 1 return this.n } } void main() { var c = Counter { n = 0 } print(c.bump()) } .fi .RE .PP .RS 4 .nf error: a method is not called by C: `export` is written on a function at the top level --> example.sg:4:5 4 | export int bump(ref this) { | ^^^^^^ hint: C reaches a value through the pointer it is given: `export void step(raw void data) { var s = unsafe (ref State)data ... }` .fi .RE .SS "An async function" .RS 4 .nf export async int later() { return 1 } async void main() { print(await later()) } .fi .RE .PP .RS 4 .nf error: a function that C calls is not async: C cannot wait for a task --> example.sg:1:1 1 | export async int later() { | ^^^^^^ hint: start the work with `Task.run` inside it, or call it from SG .fi .RE .SS "One name in two modules" The file scores/a/a.sg: .PP .RS 4 .nf public export int score(int x) { return x } .fi .RE .PP The file scores/b/b.sg: .PP .RS 4 .nf export int score(int x) { return x * 2 } public int scoreB(int x) { return score(x) } .fi .RE .PP The file scores/main.sg: .PP .RS 4 .nf use a use b void main() { print(score(3)) print(scoreB(3)) } .fi .RE .PP .RS 4 .nf $ cd scores $ sg main.sg error: C would see two functions named `score` C sees the name of an `export` function as it is written, without its module --> b/b.sg:1:12 1 | export int score(int x) { | ^^^^^ the other one: --> a/a.sg:1:19 1 | public export int score(int x) { | ^^^^^ .fi .RE .PP Two functions of SG of one name in two modules are fine; C has one space of names for the whole program, so an \fBexport\fR function takes a name no other one has. .SH "SEE ALSO" .BR sg-extern (7), .BR sg-unsafe (7), .BR sg-raw (7), .BR sg-struct (7), .BR sg-pointer (7), .BR sg-build (1) .PP https://sg\-lang.org/reference/export.html