Go back

Compiling C in Bun with TypeScript: Fast, Native, and Simple

Jan 24, 2025

Learn how to compile and use C code directly in TypeScript using Bun's FFI feature, with practical examples and performance insights.


I used to think compiling C code with TypeScript would be complex. Thanks to Bun's FFI feature, it's surprisingly simple and blazingly fast. Here's how to do it:

Setup First: Avoid TypeScript Errors

Run bun init to initialize a project. This creates the scaffolding for TypeScript support:

bun init -y  # Skip prompts

Why Compile C in TypeScript?

Need C's raw performance in JavaScript? Bun v1.2's bun:ffi lets you compile C code directly in TypeScript. No WebAssembly sandboxes, no node-gyp builds—just native speed.

Hello World in TypeScript

Create hello.c:

#include <stdio.h>
void hello(const char* name) {
  printf("Hello %s from C!\n", name);
}

Write TypeScript (main.ts):

import { cc } from "bun:ffi";

// Type-safe FFI definition
const { symbols: { hello } } = cc({
  source: "./hello.c",
  symbols: {
    hello: {
      args: ["cstring"],
      returns: "void"
    }
  } as const,
});

// Create a CString from TypeScript string
const name = "World";
const cString = Buffer.from(name);

hello(cString); // Output: "Hello World from C!"

Run it:

bun run main.ts

Performance & Use Cases

Speed: ~6.26ns/call (2ns Bun overhead).

Practical uses:

  • Access system APIs (macOS Keychain, Windows Registry)
  • Optimize math-heavy logic (e.g., prime checks, video encoding)

Gotchas

  • TinyCC limitations: No GCC/Clang optimizations
  • Experimental: Thread safety and async callbacks are WIP
  • String encoding defaults to UTF-8

Quick Start

Install Bun and initialize:

curl -fsSL https://bun.sh/install | bash
bun init -y  # Critical for TypeScript support

Add the hello.c and main.ts examples.

Like this post? Share it or follow me on my blog for more guides.

References: Bun FFI Docs, Bun Blog.