Star 历史趋势
数据来源: GitHub API · 生成自 Stargazers.cn
README.md

Zen C

Modern Ergonomics. Zero Overhead. Pure C.


Build Status License Version Platform

Write like a high-level language, run like C.



Overview

Zen C is a modern systems programming language that compiles to human-readable GNU C/C11. It provides a rich feature set including type inference, pattern matching, generics, traits, async/await, and manual memory management with RAII capabilities, all while maintaining 100% C ABI compatibility.

Community

Join the discussion, share demos, ask questions, or report bugs in the official Zen C Discord server!

Ecosystem

The Zen C project consists of several repositories. Below you can find the primary ones:

RepositoryDescriptionStatus
zencThe core Zen C compiler (zc), CLI, and Standard Library.Active Development
docsThe official documentation and language specification.Active
rfcsThe Request for Comments (RFC) repository. Shape the future of the language.Active
vscode-zencOfficial VS Code extension (Syntax Highlighting, Snippets).Alpha
wwwSource code for zenc-lang.org.Active
awesome-zencA curated list of awesome Zen C examplesGrowing
zenc.vimOfficial Vim/Neovim plugin (Syntax, Indentation).Active

Showcase

Check out these projects built with Zen C:

  • ZC-pong-3ds: A Pong clone for the Nintendo 3DS.
  • zen-c-parin: A basic example using Zen C with Parin.
  • almond: A minimal web browser written in Zen C.

Index

GeneralLanguage Reference

Browse the Language Reference


Quick Start

Installation

git clone https://github.com/zenc-lang/zenc.git cd Zen-C make clean # remove old build files make sudo make install

Windows

Zen C has full native support for Windows (x86_64). You can build using the provided batch script with GCC (MinGW):

build.bat

This will build the compiler (zc.exe). Networking, Filesystem, and Process operations are fully supported via the Platform Abstraction Layer (PAL).

Alternatively, you can use make if you have a Unix-like environment (MSYS2, Cygwin, git-bash).

Portable Build (APE)

Zen C can be compiled as an Actually Portable Executable (APE) using Cosmopolitan Libc. This produces a single binary (.com) that runs natively on Linux, macOS, Windows, FreeBSD, OpenBSD, and NetBSD on both x86_64 and aarch64 architectures.

Prerequisites:

  • cosmocc toolchain (must be in your PATH)

Build & Install:

make ape sudo env "PATH=$PATH" make install-ape

Artifacts:

  • out/bin/zc.com: The portable Zen-C compiler. Includes the standard library embedded within the executable.
  • out/bin/zc-boot.com: A self-contained bootstrap installer for setting up new Zen-C projects.

Usage:

# Run on any supported OS ./out/bin/zc.com build hello.zc -o hello

Usage

# Compile and run zc run hello.zc # Build executable zc build hello.zc -o hello # Interactive Shell zc repl # Show Zen Facts zc build hello.zc --zen

Environment Variables

You can set ZC_ROOT to specify the location of the Standard Library (standard imports like import "std/vec.zc"). This allows you to run zc from any directory.

export ZC_ROOT=/path/to/Zen-C

Language Reference

See the official Language Reference for more details.

Standard Library

Zen C includes a standard library (std) covering essential functionality.

Browse the Standard Library Documentation

Key Modules

Click to see all Standard Library modules
ModuleDescriptionDocs
std/bigfloat.zcArbitrary-precision floating-point arithmetic.Docs
std/bigint.zcArbitrary-precision integer BigInt.Docs
std/bits.zcLow-level bitwise operations (rotl, rotr).Docs
std/complex.zcComplex Number Arithmetic Complex.Docs
std/vec.zcGrowable dynamic array Vec<T>.Docs
std/string.zcHeap-allocated String type with UTF-8 support.Docs
std/queue.zcFIFO queue (Ring Buffer).Docs
std/map.zcGeneric Hash Map Map<V>.Docs
std/fs.zcFile system operations.Docs
std/io.zcStandard Input/Output (print/println).Docs
std/option.zcOptional values (Some/None).Docs
std/result.zcError handling (Ok/Err).Docs
std/path.zcCross-platform path manipulation.Docs
std/env.zcProcess environment variables.Docs
std/net/TCP, UDP, HTTP, DNS, URL.Docs
std/thread.zcThreads and Synchronization.Docs
std/time.zcTime measurement and sleep.Docs
std/json.zcJSON parsing and serialization.Docs
std/stack.zcLIFO Stack Stack<T>.Docs
std/set.zcGeneric Hash Set Set<T>.Docs
std/process.zcProcess execution and management.Docs
std/regex.zcRegular Expressions (TRE based).Docs
std/simd.zcNative SIMD vector types.Docs

18. Unit Testing Framework

Zen C features a built-in testing framework that allows you to write unit tests directly in your source files using the test keyword.

Syntax

A test block contains a descriptive name and a body of code to execute. Tests do not require a main function to run.

test "unittest1" { "This is an unittest"; let a = 3; assert(a > 0, "a should be a positive integer"); "unittest1 passed."; }

Running Tests

To run all tests in a file, use the run command. The compiler will automatically detect and execute all top-level test blocks.

zc run my_file.zc

Assertions

Use the built-in assert(condition, message) function to verify expectations. If the condition is false, the test will fail and print the provided message.


Tooling

Zen C provides a built-in Language Server and REPL to enhance the development experience. It is also debuggable with LLDB.

Language Server (LSP)

The Zen C Language Server (LSP) supports standard LSP features for editor integration, providing:

  • Go to Definition
  • Find References
  • Hover Information
  • Completion (Function/Struct names, Dot-completion for methods/fields)
  • Document Symbols (Outline)
  • Signature Help
  • Diagnostics (Syntax/Semantic errors)

To start the language server (typically configured in your editor's LSP settings):

zc lsp

It communicates via standard I/O (JSON-RPC 2.0).

REPL

The Read-Eval-Print Loop allows you to experiment with Zen C code interactively.

zc repl

Features

  • Interactive Coding: Type expressions or statements for immediate evaluation.
  • Persistent History: Commands are saved to ~/.zprep_history.
  • Startup Script: Auto-loads commands from ~/.zprep_init.zc.

Commands

CommandDescription
:helpShow available commands.
:resetClear current session history (variables/functions).
:varsShow active variables.
:funcsShow user-defined functions.
:structsShow user-defined structs.
:importsShow active imports.
:historyShow session input history.
:type <expr>Show the type of an expression.
:c <stmt>Show the generated C code for a statement.
:time <expr>Benchmark an expression (runs 1000 iterations).
:edit [n]Edit command n (default: last) in $EDITOR.
:save <file>Save the current session to a .zc file.
:load <file>Load and execute a .zc file into the session.
:watch <expr>Watch an expression (re-evaluated after every entry).
:unwatch <n>Remove a watch.
:undoRemove the last command from the session.
:delete <n>Remove command at index n.
:clearClear the screen.
:quitExit the REPL.
! <cmd>Run a shell command (e.g. !ls).

Language Server Protocol (LSP)

Zen C includes a built-in Language Server for editor integration.

Use zc lsp to start the server.

Debugging Zen C

Zen C programs can be debugged using standard C debuggers like LLDB or GDB.

Visual Studio Code

For the best experience in VS Code, install the official Zen C extension. For debugging, you can use the C/C++ (by Microsoft) or CodeLLDB extension.

Add these configurations to your .vscode directory to enable one-click debugging:

tasks.json (Build Task):

{ "label": "Zen C: Build Debug", "type": "shell", "command": "zc", "args": [ "${file}", "-g", "-o", "${fileDirname}/app", "-O0" ], "group": { "kind": "build", "isDefault": true } }

launch.json (Debugger):

{ "name": "Zen C: Debug (LLDB)", "type": "lldb", "request": "launch", "program": "${fileDirname}/app", "preLaunchTask": "Zen C: Build Debug" }

Compiler Support & Compatibility

Zen C is designed to work with most C11 compilers. Some features rely on GNU C extensions, but these often work in other compilers. Use the --cc flag to switch backends.

zc run app.zc --cc clang zc run app.zc --cc zig

Test Suite Status

Click to view Compiler Support details
CompilerPass RateSupported FeaturesKnown Limitations
GCC100% (Full)All FeaturesNone.
Clang100% (Full)All FeaturesNone.
Zig100% (Full)All FeaturesNone. Uses zig cc as a drop-in C compiler.
TCC98% (High)Structs, Generics, Traits, Pattern MatchingNo Intel ASM, No __attribute__((constructor)).

[!WARNING] COMPILER BUILD WARNING: While Zig CC works excellently as a backend for your Zen C programs, building the Zen C compiler itself with it may verify but produce an unstable binary that fails tests. We recommend building the compiler with GCC or Clang and using Zig only as a backend for your operational code.

Building with Zig

Zig's zig cc command provides a drop-in replacement for GCC/Clang with excellent cross-compilation support. To use Zig:

# Compile and run a Zen C program with Zig zc run app.zc --cc zig # Build the Zen C compiler itself with Zig make zig

C++ Interop

Zen C can generate C++-compatible code with the --cpp flag, allowing seamless integration with C++ libraries.

# Direct compilation with g++ zc app.zc --cpp # Or transpile for manual build zc transpile app.zc --cpp g++ out.c my_cpp_lib.o -o app

Using C++ in Zen C

Include C++ headers and use raw blocks for C++ code:

include <vector> include <iostream> raw { std::vector<int> make_vec(int a, int b) { return {a, b}; } } fn main() { let v = make_vec(1, 2); raw { std::cout << "Size: " << v.size() << std::endl; } }

[!NOTE] The --cpp flag switches the backend to g++ and emits C++-compatible code (uses auto instead of __auto_type, function overloads instead of _Generic, and explicit casts for void*).

CUDA Interop

Zen C supports GPU programming by transpiling to CUDA C++. This allows you to leverage powerful C++ features (templates, constexpr) within your kernels while maintaining Zen C's ergonomic syntax.

# Direct compilation with nvcc zc run app.zc --cuda # Or transpile for manual build zc transpile app.zc --cuda -o app.cu nvcc app.cu -o app

CUDA-Specific Attributes

AttributeCUDA EquivalentDescription
@global__global__Kernel function (runs on GPU, called from host)
@device__device__Device function (runs on GPU, called from GPU)
@host__host__Host function (explicit CPU-only)

Kernel Launch Syntax

Zen C provides a clean launch statement for invoking CUDA kernels:

launch kernel_name(args) with { grid: num_blocks, block: threads_per_block, shared_mem: 1024, // Optional stream: my_stream // Optional };

This transpiles to: kernel_name<<<grid, block, shared, stream>>>(args);

Writing CUDA Kernels

Use Zen C function syntax with @global and the launch statement:

import "std/cuda.zc" @global fn add_kernel(a: float*, b: float*, c: float*, n: int) { let i = thread_id(); if i < n { c[i] = a[i] + b[i]; } } fn main() { def N = 1024; let d_a = cuda_alloc<float>(N); let d_b = cuda_alloc<float>(N); let d_c = cuda_alloc<float>(N); defer cuda_free(d_a); defer cuda_free(d_b); defer cuda_free(d_c); // ... init data ... launch add_kernel(d_a, d_b, d_c, N) with { grid: (N + 255) / 256, block: 256 }; cuda_sync(); }

Standard Library (std/cuda.zc)

Zen C provides a standard library for common CUDA operations to reduce raw blocks:

import "std/cuda.zc" // Memory management let d_ptr = cuda_alloc<float>(1024); cuda_copy_to_device(d_ptr, h_ptr, 1024 * sizeof(float)); defer cuda_free(d_ptr); // Synchronization cuda_sync(); // Thread Indexing (use inside kernels) let i = thread_id(); // Global index let bid = block_id(); let tid = local_id();

[!NOTE] Note: The --cuda flag sets nvcc as the compiler and implies --cpp mode. Requires the NVIDIA CUDA Toolkit.

C23 Support

Zen C supports modern C23 features when using a compatible backend compiler (GCC 14+, Clang 14+, TCC (partial)).

  • auto: Zen C automatically maps type inference to standard C23 auto if __STDC_VERSION__ >= 202300L.
  • _BitInt(N): Use iN and uN types (e.g., i256, u12, i24) to access C23 arbitrary-width integers.

Objective-C Interop

Zen C can compile to Objective-C (.m) using the --objc flag, allowing you to use Objective-C frameworks (like Cocoa/Foundation) and syntax.

# Compile with clang (or gcc/gnustep) zc app.zc --objc --cc clang

Using Objective-C in Zen C

Use include for headers and raw blocks for Objective-C syntax (@interface, [...], @"").

//> macos: framework: Foundation //> linux: cflags: -fconstant-string-class=NSConstantString -D_NATIVE_OBJC_EXCEPTIONS //> linux: link: -lgnustep-base -lobjc include <Foundation/Foundation.h> fn main() { raw { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSLog(@"Hello from Objective-C!"); [pool drain]; } println "Zen C works too!"; }

[!NOTE] Note: Zen C string interpolation works with Objective-C objects (id) by calling debugDescription or description.


Contributing

We welcome contributions! Whether it's fixing bugs, adding documentation, or proposing new features.

Please see CONTRIBUTING.md for detailed guidelines on how to contribute, run tests, and submit pull requests.


Security

For security reporting instructions, please see SECURITY.md.


Attributions

This project uses third-party libraries. Full license texts can be found in the LICENSES/ directory.

  • cJSON (MIT License): Used for JSON parsing and generation in the Language Server.
  • zc-ape (MIT License): The original Actually Portable Executable port of Zen-C by Eugene Olonov.
  • Cosmopolitan Libc (ISC License): The foundational library that makes APE possible.
  • TRE (BSD License): Used for the regular expression engine in the standard library.
  • zenc.vim (MIT License): The official Vim/Neovim plugin, primarily authored by davidscholberg.

Copyright © 2026 Zen C Programming Language.
Start your journey today.

DiscordGitHubDocumentationExamplesRFCsContribute

关于 About

Write like a high-level language, run like C.
ccompilerlspopen-sourceprogramming-languagesrepltranspilerzen-c

语言 Languages

C98.7%
Shell0.4%
Makefile0.4%
CMake0.3%
Batchfile0.1%
Nix0.0%

提交活跃度 Commit Activity

代码提交热力图
过去 52 周的开发活跃度
800
Total Commits
峰值: 129次/周
Less
More

核心贡献者 Contributors