C Compiler - BunDocumentation Index Search...⌘KInstall Bun Search...Navigation Interop & Tooling C CompilerRuntimePackage ManagerBundlerTest RunnerGuidesReferenceBlogFeedback:first-child]:!hidden peer-[.is-custom]:[&>:first-child]:sm:!hidden peer-[.is-custom]:[&>:first-child]:md:!hidden peer-[.is-custom]:[&>:first-child]:lg:!hidden peer-[.is-custom]:[&>:first-child]:xl:!hidden">Get StartedWelcome to BunInstallationQuickstartTypeScriptTypeScript 6 and 7bun initbun createCore RuntimeBun RuntimeWatch ModeDebuggingREPLbunfig.tomlFile & Module SystemFile TypesModule ResolutionJSXAuto-installPluginsFile System RouterHTTP serverServerRoutingCookiesTLSError HandlingMetricsNetworkingFetchWebSocketsTCPUDPDNSData & StorageCookiesFile I/OStreamsBinary DataArchiveSQLSQLiteS3RedisConcurrencyWorkersProcess & SystemEnvironment VariablesShellSpawnWebViewCronInterop & ToolingNode-APIFFIC CompilerTranspilerUtilitiesCSRF ProtectionSecretsConsoleTOMLYAMLMarkdownJSON5JSONLHTMLRewriterImageHashingGlobSemverColorUtilsStandards & CompatibilityGlobalsBun APIsWeb APIsNode.js CompatibilityContributingRoadmapBenchmarkingContributingBuilding WindowsBindgenLicense On this pageUsage (cc in bun:ffi)Primitive typesStrings, objects, and non-primitive typesReturning a C string to JavaScriptcc Referencelibrary: string[]symbolssourceflags: string | string[]define: RecordInterop & ToolingC Compiler Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_n4ctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed"> *]:[overflow-wrap:anywhere]"> Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_1cctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed"> bun:ffi has experimental support for compiling and running C from JavaScript with low overhead.
Usage (cc in bun:ffi)
See the introduction blog post for more information.
JavaScript:
hello.ts Yes NoSuggest editsRaise issueFFIPreviousTranspilerNext⌘I xgithubdiscordyoutubePowered byThis documentation is built and hosted on Mintlify, a developer documentation platform
Fetch the complete documentation index at: /docs/llms.txt
Use this file to discover all available pages before exploring further.
Skip to main contentBun home pageCompile and run C from JavaScript with low overhead
import { cc } from "bun:ffi";
import source from "./hello.c" with { type: "file" };
const {
symbols: { hello },
} = cc({
source,
symbols: {
hello: {
args: [],
returns: "int",
},
},
});
console.log("What is the answer to the universe?", hello());
C source:
hello.cint hello() {
return 42;
}
When you run hello.js, it will print:
terminalbun hello.js What is the answer to the universe? 42Under the hood, cc uses TinyCC to compile the C code and then link it with the JavaScript runtime, efficiently converting types in-place. Primitive types The same FFIType values in dlopen are supported in cc. FFITypeC TypeAliasescstringchar*function(void*)(*)()fn, callbackptrvoid*pointer, void*, char*i8int8_tint8_ti16int16_tint16_ti32int32_tint32_t, inti64int64_tint64_ti64_fastint64_tu8uint8_tuint8_tu16uint16_tuint16_tu32uint32_tuint32_tu64uint64_tuint64_tu64_fastuint64_tf32floatfloatf64doubledoubleboolboolcharcharnapi_envnapi_envnapi_valuenapi_value Strings, objects, and non-primitive types To make it easier to work with strings, objects, and other non-primitive types that don’t map 1:1 to C types, cc supports N-API. To pass or receive a JavaScript values without any type conversions from a C function, you can use napi_value. You can also pass a napi_env to receive the N-API environment used to call the JavaScript function. Returning a C string to JavaScript For example, if you have a string in C, you can return it to JavaScript like this: hello.ts
import { cc } from "bun:ffi";
import source from "./hello.c" with { type: "file" };
const {
symbols: { hello },
} = cc({
source,
symbols: {
hello: {
args: ["napi_env"],
returns: "napi_value",
},
},
});
const result = hello();
And in C:
hello.c#include node/node_api.h>
napi_value hello(napi_env env) {
napi_value result;
napi_create_string_utf8(env, "Hello, Napi!", NAPI_AUTO_LENGTH, &result);
return result;
}
You can also use this to return other types like objects and arrays:
hello.c#include node/node_api.h>
napi_value hello(napi_env env) {
napi_value result;
napi_create_object(env, &result);
return result;
}
cc Reference
library: string[]
Use the library array to specify the libraries to link with the C code.
type Library = string[];
cc({
source: "hello.c",
library: ["sqlite3"],
});
symbols
Use the symbols object to specify the functions and variables to expose to JavaScript.
type Symbols = {
[key: string]: {
args: FFIType[];
returns: FFIType;
};
};
source
The source is a file path to the C code that should be compiled and linked with the JavaScript runtime.
type Source = string | URL | BunFile;
cc({
source: "hello.c",
symbols: {
hello: {
args: [],
returns: "int",
},
},
});
flags: string | string[]
The flags is an optional array of strings that should be passed to the TinyCC compiler.
type Flags = string | string[];These are flags like -I for include directories and -D for preprocessor definitions. ">define: Record The define is an optional object that should be passed to the TinyCC compiler.
type Defines = Recordstring, string>;
cc({
source: "hello.c",
define: {
NDEBUG: "1",
},
});
These are preprocessor definitions passed to the TinyCC compiler.Was this page helpful?
C Compiler - Bun,AI智能索引,全网链接索引,智能导航,网页索引
- Compile and run C from JavaScript with low overhead