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

Gentrit Biba @gentritbiba

About: I'm a passionate software developer with a knack for crafting intuitive web experiences that blend functionality and design.

Joined:
Dec 31, 2019

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

Publish Date: Jan 25
2 0

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
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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!"
Enter fullscreen mode Exit fullscreen mode

Run it:

bun run main.ts
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Comments 0 total

    Add comment