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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay