Files
rexlang/docs/13-c-libraries.md
T
Your NameandClaude Opus 5.5 7cf9727bcd Rename the language from Dino to Rex
Files use .rex, the command is rex, and the crate, runtime prefixes,
docs, editor files and examples all use the new name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:51:23 +01:00

305 lines
8.6 KiB
Markdown

# 13. C and C++ libraries
A huge amount of useful code is written in C: graphics (raylib, SDL), compression (zlib),
databases (SQLite), and the C library that comes with every system. Rex can use it
directly. You don't write any declarations: Rex reads the library's **header file** (the
`.h` file that lists what the library has) and works out the rest.
## Importing a header
Put the header's name in quotes. Its functions, types and constants are then used with the
header's name in front, the same way as your own files (`import utils` gives `utils.name`).
```rex
import "string.h"
import "stdlib.h"
func main() {
print(string.strlen("hello"))
print(stdlib.abs(-7), stdlib.atoi("42") + 1)
}
```
```text
5
7 43
```
The name in front is the file name without `.h`: `"zlib.h"` gives `zlib`, `"SDL2/SDL.h"`
gives `SDL`, `"my-lib.h"` gives `my_lib`. To choose another one, write it before the quotes:
`import z "zlib.h"` gives `z.crc32(...)`.
## Picking a few names
When you only want some things from a header, list them in braces. Those names are then
used **without** a prefix, and nothing else from the header is visible:
```rex
import "math.h" { cbrt, hypot }
func main() {
print(cbrt(27.0), hypot(3.0, 4.0))
}
```
```text
3.0 5.0
```
(`math.h` is the C math library. Rex's own `import math` is usually nicer; this is just a
small example.)
## How C types look in Rex
| In C | In Rex |
|------|---------|
| `int`, `unsigned int`, `short`, ... | `i32`, `u32`, `i16`, ... |
| `long`, `long long`, `int64_t` | `int` |
| `size_t`, `unsigned long`, `uint64_t` | `u64` |
| `double` / `float` | `float` / `f32` |
| `char` | `i8` (you can pass a character like `'a'`) |
| `bool` | `bool` |
| `const char *` and `char *` | `string` |
| an `enum` | its values are constants (`i32`) |
| a `struct` with plain fields | a Rex struct: `raylib.Color{255, 0, 0, 255}` |
| any other pointer (`FILE *`, `SDL_Window *`) | a pointer type: `stdio.FILE`, `SDL.SDL_Window` |
| `NULL` | `nil` |
Numbers follow the usual Rex rule: a number written in the code fits any number type, but
a variable has to be converted, for example `i32(n)` when the C function takes an `int`.
Text works both ways: a Rex string is handed to C as a C string, and a C string that comes
back becomes a Rex string (a copy, so it stays valid).
## Pointers: things you only pass around
Many C libraries give you a pointer to something they manage, like an open file or a
window. In Rex you keep it in a variable, hand it back to the library, and compare it with
`nil` to see if it is missing:
```rex
import "stdio.h"
import os
func main() {
var f = stdio.fopen("/tmp/rex-hello.txt", "w")
if f == nil {
print("can't open the file")
return
}
stdio.fputs("hello from C\n", f)
stdio.fclose(f)
var text, err = os.read_file("/tmp/rex-hello.txt")
print(text.trim(), err)
}
```
```text
hello from C nil
```
The type can be written like any other: `var f: stdio.FILE` starts out as `nil`.
**Rex does not free C things for you.** Whatever the library opens or creates, close or
free it with the library's own function (`fclose`, `sqlite3_close`, `UnloadTexture`, ...).
## Functions that write into your variables
Some C functions give back extra results by writing into a variable you pass them (in C:
a pointer parameter like `double *out`). Pass a Rex **variable**, and the function changes
it. Pass a **list** where the C function wants room for several values (a buffer):
```rex
import "math.h" { modf }
import "string.h" { memset }
func main() {
var whole = 0.0
var frac = modf(3.75, whole) // modf writes the whole part into `whole`
print(frac, whole)
var buf: []u8 = [0, 0, 0]
memset(buf, 65, 3) // fills the list's items
print(buf)
}
```
```text
0.75 3.0
[65, 65, 65]
```
A list given to C must already have as many items as the function will write; the C
function can't make it longer.
The same goes for libraries that hand you a new pointer through a parameter (in C:
`sqlite3 **db`). Make a variable of that pointer type and pass it; afterwards it is set:
```text
var db: sqlite3.sqlite3
sqlite3.sqlite3_open("notes.db", db) // db is now open (or still nil if it failed)
```
## Constants
Values from `#define` and `enum` work like Rex constants: `stdio.EOF`, `zlib.Z_OK`,
`raylib.KEY_SPACE`. raylib's colours (`raylib.RED`, `raylib.RAYWHITE`) are struct constants
of type `raylib.Color`.
## Linking: where the library's code is
The header only describes a library; its code is in a library file that has to be linked
in. Rex asks the system (`pkg-config`) for that, so for most installed libraries
`import "raylib.h"` or `import "zlib.h"` is all you need. If a library isn't known to
`pkg-config`, name it yourself: for the file `libfoo.so`, write
```text
import "foo.h" link "foo"
```
If it is missing, building stops with a message that says so.
## A window with raylib
[raylib](https://www.raylib.com) is a simple library for games and graphics. With it
installed, this opens a window and draws a circle:
```rex
import "raylib.h"
func main() {
raylib.InitWindow(800, 450, "Hello from Rex")
raylib.SetTargetFPS(60)
var x: f32 = 400.0
for !raylib.WindowShouldClose() {
if raylib.IsKeyDown(raylib.KEY_RIGHT) { x += 4.0 }
if raylib.IsKeyDown(raylib.KEY_LEFT) { x -= 4.0 }
raylib.BeginDrawing()
raylib.ClearBackground(raylib.RAYWHITE)
raylib.DrawCircleV(raylib.Vector2{x, 225.0}, 40.0, raylib.MAROON)
raylib.DrawText("arrow keys move the ball", 10, 10, 20, raylib.DARKGRAY)
raylib.EndDrawing()
}
raylib.CloseWindow()
}
```
A bigger example with bouncing balls is in
[`examples/c/bounce.rex`](../examples/c/bounce.rex).
## Your own C code
Put a header and its `.c` file next to your program. `import "shapes.h"` reads the header,
and Rex compiles `shapes.c` and builds it into your program.
```c
// shapes.h
typedef struct { double w, h; } Size;
double area(Size s);
void grow(Size *s, double by);
```
```c
// shapes.c
#include "shapes.h"
double area(Size s) { return s.w * s.h; }
void grow(Size *s, double by) { s->w *= by; s->h *= by; }
```
```rex
import "shapes.h"
func main() {
var s = shapes.Size{2.0, 3.0}
shapes.grow(s, 10.0) // grow changes `s`
print(shapes.area(s), s.w)
}
```
```text
600.0 20.0
```
## C++
C++ code can't be called from C or Rex directly: C++ functions get scrambled ("mangled")
names when compiled, and classes and templates don't exist in C. The usual fix is a small
set of plain functions marked `extern "C"`. Write them in a `.cpp` file next to the header,
and Rex compiles it with your C++ compiler (`c++`) and links in the C++ library:
```c
// counter.h: plain C, also readable by C++
#ifdef __cplusplus
extern "C" {
#endif
typedef struct Counter Counter;
Counter *counter_new(void);
void counter_add(Counter *c, int n);
int counter_total(const Counter *c);
void counter_free(Counter *c);
#ifdef __cplusplus
}
#endif
```
```cpp
// counter.cpp: free to use any C++ inside
#include "counter.h"
#include <numeric>
#include <vector>
struct Counter { std::vector<int> items; };
extern "C" {
Counter *counter_new(void) { return new Counter{}; }
void counter_add(Counter *c, int n) { c->items.push_back(n); }
int counter_total(const Counter *c) { return std::accumulate(c->items.begin(), c->items.end(), 0); }
void counter_free(Counter *c) { delete c; }
}
```
```rex
import "counter.h"
func main() {
var c = counter.counter_new()
for i in 1..5 { counter.counter_add(c, i32(i)) }
print(counter.counter_total(c))
counter.counter_free(c)
}
```
```text
10
```
The same trick works for a big C++ library: wrap the few things you need in `extern "C"`
functions.
## Seeing what a header has
`rex header` lists everything Rex can use from a header, written as Rex. Add a word to
only see names that contain it:
```text
rex header zlib.h compress
```
```text
import "zlib.h" // use the names below as zlib.name
// builds with: -DWITH_GZFILEOP -lz
// functions
func compress(dest: []u8 or u8 variable, destLen: []u64 or u64 variable, source: []u8 or u8, sourceLen: u64): i32
...
```
In an editor with Rex support, completion after `zlib.` and hovering a name show the same.
## What doesn't work yet
Rex tells you when you call one of these, and why:
- functions with a variable number of arguments, like `printf`
- functions that take a callback (a function pointer)
- `union` types, and structs with arrays inside (you can still pass pointers to them)
- a list of structs where C wants several structs in a row
- C macros that take arguments (`#define MAX(a, b) ...`)
When you need one of these, write a small function in your own `.c` file that does the C
part, and call that from Rex.
Next: back to the [overview](README.md)