ffi qjs-ffi

cc(): compile and run C from JavaScript

cc() compiles C source in memory with TinyCC (libtcc) and returns the functions you ask for as plain, directly-callable JavaScript functions. It follows bun:ffi's cc(), minus the N-API parts.

It is only available when the ffi module was built with -DENABLE_TCC=ON (see Building); otherwise ffi does not export cc at all.

Usage

JavaScript:

import { cc } from 'ffi';

const {
  symbols: { hello },
} = cc({
  source: 'hello.c',
  symbols: {
    hello: {
      args: [],
      returns: 'int',
    },
  },
});

console.log('What is the answer to the universe?', hello());

C source:

/* hello.c */
int hello() {
  return 42;
}

Running it prints:

What is the answer to the universe? 42

cc() compiles the code straight into memory, links it with the running process (so libc and everything already loaded is available to the C code) and wraps each requested function in a CFunction, so a call goes through libffi with the signature you declared.

Reference

cc(options) takes a single options object and returns { symbols }.

source

Where the C code comes from:

type Source = string | ArrayBuffer | TypedArray | DataView;
  • A string is the path of a C file to compile. A relative path is resolved against the current working directory.
  • Anything else is taken to be a view holding the C source text (UTF-8 bytes), which is copied and compiled as it is. A Uint8Array or DataView over a part of a buffer compiles just that part. Use this to compile code that is embedded in, or generated by, the script:
const code = std.loadFile('hello.c');   // or a template literal, etc.
const bytes = Uint8Array.from(code, (c) => c.charCodeAt(0));

cc({ source: bytes, symbols: { hello: { args: [], returns: 'i32' } } });

A missing source, or one that is neither a string nor a view, throws a TypeError.

symbols

The functions to expose to JavaScript, by their name in the C source:

type Symbols = {
  [name: string]: {
    args: FFIType[];
    returns: FFIType;
    abi?: string;
  };
};

This is the same spec as CFunction and dlopen() take (minus ptr, which cc() fills in with the compiled function's address), so the type table, structs by value and ABI names documented there apply unchanged. Every name must exist in the compiled code, or cc() throws a TypeError (cc: symbol not found: <name>).

A spec with type instead of args/returns exposes a variable, which bun does not (its symbols is typed Record<string, FFIFunction>); see Variables. cc() code is never freed, so such an address stays valid.

types

An optional object of classes, { Point }: a "Point *" in symbols is then a pointer typed by Point. An extension.

library

type Library = string | string[];

cc({ source: 'hello.c', library: ['sqlite3'], symbols: { /* ... */ } });

Libraries to link the C code against, as for -l ("sqlite3" finds libsqlite3.so). TinyCC searches its default library paths; add -L<dir> to flags for others.

include

type Include = string | string[];

cc({ source: 'hello.c', include: ['vendor/include'], symbols: { /* ... */ } });

Directories searched for #include "..." and #include <...>, as for -I (ffi.d.ts of Bun has it; its docs page does not). Same as -I<dir> in flags.

flags

type Flags = string | string[];

Options handed to TinyCC, such as -I<dir> for include directories, -D for preprocessor definitions, -L<dir> for library directories or -W... for warnings. A string may hold several options separated by spaces (`"-DA=1 -DB=2"`); an array holds one option, or one group, per element.

define

type Defines = Record<string, string>;

cc({ source: 'hello.c', define: { NDEBUG: '1' }, symbols: { /* ... */ } });

Preprocessor definitions, equivalent to -DNAME=value in flags. Values are strings.

Return value

{ symbols: { [name: string]: Function } }

One function per entry of symbols, in the same order.

Types

cc() shares the type table: "i8" ... "u64", "i64_fast", "u64_fast", "f32", "f64", "bool", "pointer" ("ptr", "function", and any name ending in *), "cstring" and, for structs passed or returned by value, an array of member types. Bun's C-style aliases work too: "int", "int32_t", "uint8_t", "float", "double", "isize", "usize", "char", "buffer", "fn", "callback" ...

const { symbols } = cc({
  source: bytes, // double hyp(double a, double b) { return sqrt(a*a + b*b); }
  library: 'm',
  symbols: { hyp: { args: ['f64', 'f64'], returns: 'f64' } },
});

symbols.hyp(3, 4); // 5

Strings are passed with "cstring", and are valid only for the duration of the call. There is no N-API: Bun's napi_env and napi_value types, which let C create and receive JavaScript values directly, do not exist here.

Errors

SituationThrown
options not an object, symbols missing, source missing or of a wrong typeTypeError
C does not compile (syntax error, unresolved reference, unreadable file, bad option)InternalError, the message carrying TinyCC's diagnostics (first 1 KiB)
a name in symbols not defined by the codeTypeError

Lifetime

The compiled code is never freed -- like Bun, cc() has no close(). The returned functions stay valid for as long as the process runs, and compiling the same code twice produces two independent copies.

Differences from Bun

  • source is a file name or a view of source text; Bun's URL and BunFile values, and import ... with { type: "file" }, have no equivalent here.
  • A relative source path is resolved against the working directory, not against the calling module.
  • No napi_env / napi_value.
  • Bun's --no-ffi-cc switch (and its ERR_FFI_CC_DISABLED error) does not exist; leave ENABLE_TCC off to have no cc().

Building

cc() is an opt-in build feature:

cmake -S . -B build -DENABLE_TCC=ON
cmake --build build

cmake/BuildLibTCC.cmake clones a pinned revision of upstream TinyCC into third_party/tinycc (needs git and network access the first time), builds libtcc.a and libtcc1.a from it with the module's own C compiler, and links libtcc.a into the ffi module (and into quickjs-ffi.a when BUILD_STATIC is on).

TinyCC's own runtime files (its libtcc1.a and headers such as stddef.h and stdarg.h) are looked up in the build tree's libtcc-*/install/lib/tcc; that path is compiled into the module, so a built module should be used from where it was built.

See also