DEV Community

Gentrit Biba
Gentrit Biba

Posted on

2

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

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.

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more