Build hooks and native assets

suggest change

A build hook is a Dart script, hook/build.dart, that the Dart SDK runs before your program. It compiles C code, downloads a prebuilt library or collects other files, and reports them as assets. The SDK then makes those assets available to your program: a compiled .dll/.so/.dylib is a code asset (also called a native asset), and @Native functions in Dart bind to it without any DynamicLibrary.open call.

Build hooks became stable in Dart 3.10. Dart 3.13 can cross-compile code assets: dart build cli --target-os=linux works from a Windows or macOS machine.

The dart:ffi article has a minimal @Native + build hook example. This article goes further:

All examples were run with Dart 3.13.4 on Windows 11 with Visual Studio 2026 (MSVC 19.51), using hooks 2.2.0, code_assets 2.1.0 and native_toolchain_c 0.19.5.

The packages

Package What it's for
hooks build() and link() entry points, BuildInput, BuildOutputBuilder, user-defines
code_assets CodeAsset, OS, Architecture, link modes, input.config.code
native_toolchain_c CBuilder and CLibrary: find the C compiler and run it
data_assets DataAsset for non-code files (experimental, see below)

hooks and code_assets are stable (1.0+). native_toolchain_c and data_assets are published under labs.dart.dev and still change between minor versions, so pin them with a caret constraint and read the changelog when you upgrade.

These packages are regular dependencies, not dev_dependencies: when someone depends on your package, the SDK runs your hook in their project, so its imports must resolve there.

A package that compiles C

We'll build a package mathx with three C functions:

mathx/
  pubspec.yaml
  hook/build.dart        <- the build hook
  src/mathx.c            <- C sources (outside lib/)
  lib/src/bindings.dart  <- @Native declarations
  lib/mathx.dart         <- public Dart API
  bin/mathx.dart
  test/mathx_test.dart
name: mathx
version: 1.0.0

environment:
  sdk: ^3.13.4

dependencies:
  code_assets: ^2.1.0
  ffi: ^2.2.0
  hooks: ^2.2.0
  native_toolchain_c: ^0.19.5

dev_dependencies:
  lints: ^6.0.0
  test: ^1.25.6

The C code exports its functions explicitly: on Windows a function is only visible in a DLL if it's marked __declspec(dllexport). MATHX_SEED is a macro that the hook can override:

// src/mathx.c
#include <stdint.h>
#include <stddef.h>

#if defined(_WIN32)
#define MATHX_EXPORT __declspec(dllexport)
#else
#define MATHX_EXPORT __attribute__((visibility("default")))
#endif

#ifndef MATHX_SEED
#define MATHX_SEED 2166136261u
#endif

// 32-bit FNV-1a hash of a byte buffer.
MATHX_EXPORT uint32_t mathx_fnv1a(const uint8_t *data, size_t len) {
  uint32_t h = MATHX_SEED;
  for (size_t i = 0; i < len; i++) {
    h ^= data[i];
    h *= 16777619u;
  }
  return h;
}

// Greatest common divisor.
MATHX_EXPORT int64_t mathx_gcd(int64_t a, int64_t b) {
  while (b != 0) {
    int64_t t = a % b;
    a = b;
    b = t;
  }
  return a < 0 ? -a : a;
}

MATHX_EXPORT const char *mathx_build_info(void) {
#if defined(_MSC_VER)
  return "built with MSVC";
#elif defined(__clang__)
  return "built with clang";
#elif defined(__GNUC__)
  return "built with gcc";
#else
  return "built with an unknown compiler";
#endif
}

The hook

// hook/build.dart
import 'package:code_assets/code_assets.dart';
import 'package:hooks/hooks.dart';
import 'package:native_toolchain_c/native_toolchain_c.dart';

void main(List<String> args) async {
  await build(args, (input, output) async {
    if (!input.config.buildCodeAssets) return;

    final builder = CBuilder.library(
      name: 'mathx',
      assetName: 'src/bindings.dart',
      sources: ['src/mathx.c'],
    );
    await builder.run(input: input, output: output);
  });
}

CBuilder finds a compiler on its own: MSVC through vswhere.exe on Windows (it runs vcvars to set up the environment), Xcode's clang on macOS, and clang or gcc on Linux. The user doesn't need a "Developer Command Prompt".

Binding with @Native

// lib/src/bindings.dart
import 'dart:ffi';

import 'package:ffi/ffi.dart';

@Native<Uint32 Function(Pointer<Uint8>, Size)>(
  symbol: 'mathx_fnv1a',
  isLeaf: true,
)
external int mathxFnv1a(Pointer<Uint8> data, int len);

@Native<Int64 Function(Int64, Int64)>(symbol: 'mathx_gcd', isLeaf: true)
external int mathxGcd(int a, int b);

@Native<Pointer<Utf8> Function()>(symbol: 'mathx_build_info')
external Pointer<Utf8> mathxBuildInfo();

An @Native function without an assetId: argument is looked up in the asset whose id equals the URI of the library that declares it, here package:mathx/src/bindings.dart. That's why the hook used assetName: 'src/bindings.dart'. symbol: lets you keep Dart-style names while the C names use underscores.

The public API hides the FFI details:

// lib/mathx.dart
import 'dart:convert';
import 'dart:ffi';

import 'package:ffi/ffi.dart';

import 'src/bindings.dart';

/// FNV-1a hash of the UTF-8 bytes of [s], computed in C.
int fnv1a(String s) {
  final bytes = utf8.encode(s);
  return mathxFnv1a(bytes.address, bytes.length);
}

int gcd(int a, int b) => mathxGcd(a, b);

String get buildInfo => mathxBuildInfo().toDartString();

bytes.address passes a pointer to the Dart Uint8List directly, without copying. That's allowed only for leaf @Native calls (isLeaf: true).

// bin/mathx.dart
import 'package:mathx/mathx.dart';

void main() {
  print(buildInfo);
  print('fnv1a("hello") = 0x${fnv1a('hello').toRadixString(16)}');
  print('gcd(1071, 462) = ${gcd(1071, 462)}');
}

Running it

dart run bin/mathx.dart

The first run prints Running build hooks... followed by the compiler's banner lines (on Windows, MSVC's Microsoft (R) C/C++ Optimizing Compiler...) and then the program's output. It took about 6 seconds here. With --verbosity=error the SDK's own progress messages go away:

dart run --verbosity=error bin/mathx.dart
built with MSVC
fnv1a("hello") = 0x4f9f2cab
gcd(1071, 462) = 21

On Windows the MSVC banners still appear on stderr even with --verbosity=error. They come from the compiler process, not from the SDK. The second run doesn't compile anything and took 0.9 seconds.

If the hook doesn't produce the asset (for example because the assetName doesn't match the library URI), the build succeeds but the first call fails at run time:

Unhandled exception:
Invalid argument(s): Couldn't resolve native function 'mathx_build_info' in 'package:mathx/src/bindings.dart' : No asset with id 'package:mathx/src/bindings.dart' found. Available native assets: . Attempted to fallback to process lookup. None of the loaded modules contained the requested symbol 'mathx_build_info'..

Compiler options and per-target settings

input.config.code describes the target: targetOS, targetArchitecture, linkModePreference, plus android, iOS and macOS sub-configs with SDK versions. Use it to choose sources, defines and flags:

// hook/build.dart
import 'package:code_assets/code_assets.dart';
import 'package:hooks/hooks.dart';
import 'package:native_toolchain_c/native_toolchain_c.dart';

void main(List<String> args) async {
  await build(args, (input, output) async {
    if (!input.config.buildCodeAssets) return;

    final code = input.config.code;
    print('target: ${code.targetOS} ${code.targetArchitecture}, '
        'link mode preference: ${code.linkModePreference}');

    // Optional setting from `hooks: user_defines: mathx:` in pubspec.yaml.
    final seed = input.userDefines['seed'];
    if (seed is! int?) {
      throw const FormatException('hooks.user_defines.mathx.seed must be an int');
    }

    final builder = CBuilder.library(
      name: 'mathx',
      assetName: 'src/bindings.dart',
      sources: ['src/mathx.c'],
      defines: {
        if (seed != null) 'MATHX_SEED': '${seed}u',
      },
      flags: [
        if (code.targetOS == OS.windows) '/W4' else '-Wall',
      ],
    );
    await builder.run(input: input, output: output);
  });
}

Other useful CBuilder.library parameters: includes (header directories), libraries and libraryDirectories (link against other libraries), language: Language.cpp with std: 'c++17' for C++, optimizationLevel (default .o3) and linkModePreference. By default CBuilder builds in release mode and adds -DRELEASE -DNDEBUG. With MSVC the command it ran was:

cl.exe /O2 /W4 /DMATHX_SEED=12345u /DRELEASE /DNDEBUG /LD /Fe:...\mathx.dll ...\src\mathx.c /link /MACHINE:X64 ...

Hook output doesn't appear in the terminal. print from the hook and the full compiler output go to .dart_tool/hooks_runner/mathx/<hash>/stdout.txt and stderr.txt:

target: windows x64, link mode preference: dynamic
mathx.c
Microsoft (R) Incremental Linker Version 14.51.36257.0

If compilation fails, dart run exits with code 255. The output contains the compiler error, the full command line and a "To reproduce run:" command that re-runs the hook with the same input file:

C:\...\mathx\src\mathx.c(45): error C2065: 'undefined_name': undeclared identifier
...
  Building assets for package:mathx failed.

User-defines: configuring a hook from pubspec.yaml

Hooks run in a semi-hermetic environment: most environment variables are removed, so a hook can't read MATHX_SEED from your shell. Only a fixed list is passed through, including PATH, HOME/USERPROFILE, TEMP/TMP, HTTP_PROXY/HTTPS_PROXY/NO_PROXY, the Android NDK variables and CCACHE_*. This keeps hook results reproducible and cacheable.

To pass settings to a hook, use user-defines in the pubspec.yaml of the root package (the application):

hooks:
  user_defines:
    mathx:        # the package whose hook reads these values
      seed: 12345

The hook reads them with input.userDefines['seed']. Values can be any YAML: strings, numbers, booleans, lists or maps. Validate the type yourself, as the hook above does. For file paths, use input.userDefines.path('key'), which resolves a relative path against the pubspec.yaml it came from.

Changing a user-define re-runs the hook:

built with MSVC
fnv1a("hello") = 0x5579bd97
gcd(1071, 462) = 21

Only the root package's settings count. When an app app depends on mathx (here through path: ../mathx), the seed: 12345 in mathx's own pubspec is ignored and the default seed is used, until app adds its own entry:

# app/pubspec.yaml
dependencies:
  mathx:
    path: ../mathx

hooks:
  user_defines:
    mathx:
      seed: 7
// app/bin/app.dart
import 'package:mathx/mathx.dart';

void main() {
  print('gcd(48, 180) = ${gcd(48, 180)}');
  print('fnv1a("dart") = 0x${fnv1a('dart').toRadixString(16)}');
}

Before and after adding the hooks: section:

gcd(48, 180) = 12
fnv1a("dart") = 0xef778408
gcd(48, 180) = 12
fnv1a("dart") = 0x7ddb74ae

The app didn't do anything to make the hook run: dart run runs the build hooks of every package in the dependency graph. In a pub workspace, hooks: user_defines: goes in the workspace root pubspec.yaml; entries in member packages are ignored.

Downloading prebuilt binaries

Compiling on the user's machine requires a C toolchain. Many packages instead publish precompiled libraries (for example as GitHub release files) and have the hook download the right one. package:sqlite3 works this way (see SQLite).

For that you don't need native_toolchain_c. Create the CodeAsset yourself:

// mathx_bin/hook/build.dart
import 'dart:io';

import 'package:code_assets/code_assets.dart';
import 'package:crypto/crypto.dart';
import 'package:hooks/hooks.dart';

/// Prebuilt binaries published for each supported target.
/// The hashes are part of the package source, so a tampered or
/// truncated download is rejected.
const _binaries = {
  'windows_x64': (
    file: 'mathx-windows-x64.dll',
    sha256: '308f94d4b0ae6c457ead956699e80bfc6e287dede7d69f7d3fab8bebd7900494',
  ),
  // 'linux_x64': (file: 'libmathx-linux-x64.so', sha256: '...'),
  // 'macos_arm64': (file: 'libmathx-macos-arm64.dylib', sha256: '...'),
};

const _defaultBaseUrl =
    'https://github.com/example/mathx/releases/download/v1.0.0/';

void main(List<String> args) async {
  await build(args, (input, output) async {
    if (!input.config.buildCodeAssets) return;

    final code = input.config.code;
    final binary = _binaries['${code.targetOS}_${code.targetArchitecture}'];
    if (binary == null) {
      throw UnsupportedError(
        'mathx has no prebuilt binary for '
        '${code.targetOS} ${code.targetArchitecture}',
      );
    }

    final baseUrl = input.userDefines['base_url'] as String? ?? _defaultBaseUrl;
    final target = File.fromUri(
      input.outputDirectoryShared.resolve(binary.file),
    );

    if (!await _hasHash(target, binary.sha256)) {
      final url = Uri.parse(baseUrl).resolve(binary.file);
      await _download(url, target);
      if (!await _hasHash(target, binary.sha256)) {
        await target.delete();
        throw StateError('checksum mismatch for $url');
      }
    }

    output.assets.code.add(
      CodeAsset(
        package: input.packageName,
        name: 'src/bindings.dart',
        linkMode: DynamicLoadingBundled(),
        file: target.uri,
      ),
    );
  });
}

Future<bool> _hasHash(File f, String expected) async =>
    await f.exists() && sha256.convert(await f.readAsBytes()).toString() == expected;

Future<void> _download(Uri url, File target) async {
  final client = HttpClient();
  try {
    final response = await (await client.getUrl(url)).close();
    if (response.statusCode != HttpStatus.ok) {
      throw HttpException('GET $url: ${response.statusCode}', uri: url);
    }
    await target.parent.create(recursive: true);
    await response.pipe(target.openWrite());
  } finally {
    client.close();
  }
}

Notes:

hooks:
  user_defines:
    mathx_bin:
      base_url: http://127.0.0.1:28312/
// mathx_bin/bin/mathx_bin.dart
import 'package:mathx_bin/mathx_bin.dart';

void main() {
  print('gcd(84, 36) = ${mathxGcd(84, 36)}');
}
gcd(84, 36) = 12

The server log showed one GET /mathx-windows-x64.dll for two dart run invocations: the second run reused the cached hook result. After appending one byte to the file on the server and deleting the cached copy, the hook refused it:

Unhandled exception:
Bad state: checksum mismatch for http://127.0.0.1:28312/mathx-windows-x64.dll
#0      main.<anonymous closure> (file:///.../mathx_bin/hook/build.dart:45:9)
...
  Building assets for package:mathx_bin failed.

dart run, dart test and dart build

dart run and dart test run all hooks in the dependency graph for the host machine (windows x64 here) before compiling Dart code. Tests work without extra setup:

dart test
// test/mathx_test.dart
import 'package:mathx/mathx.dart';
import 'package:test/test.dart';

void main() {
  test('gcd', () {
    expect(gcd(1071, 462), 21);
    expect(gcd(-12, 18), 6);
  });

  test('fnv1a is stable', () {
    expect(fnv1a('hello'), fnv1a('hello'));
    expect(fnv1a('hello'), isNot(fnv1a('world')));
  });
}
00:00 +0: test\mathx_test.dart: gcd
00:00 +1: test\mathx_test.dart: fnv1a is stable
00:00 +2: All tests passed!

In JIT mode the libraries are copied to .dart_tool/lib/ and the VM gets a mapping from asset id to file in .dart_tool/native_assets.yaml (reformatted):

# Native assets mapping for host OS in JIT mode.
# Generated by dartdev and package:hooks_runner.
{
  "format-version": [1, 0, 0],
  "native-assets": {
    "windows_x64": {
      "package:mathx/src/bindings.dart": [
        "absolute",
        "C:\\...\\mathx\\.dart_tool\\lib\\mathx.dll"
      ]
    }
  }
}

dart compile exe refuses to build a program whose dependencies have hooks:

'dart compile' does not support build hooks, use 'dart build' instead.
Packages with build hooks: mathx.

dart build cli compiles an AOT executable, runs the build hooks (and link hooks, see below) and creates a bundle with the libraries next to the executable:

dart build cli --verbosity=error
build/cli/windows_x64/bundle/bin/mathx.exe
build/cli/windows_x64/bundle/lib/mathx.dll

The executable finds ../lib/mathx.dll relative to itself, so ship the whole bundle directory. See Compiling to executables for the rest of dart build cli.

Caching

Each hook runs in its own directory, .dart_tool/hooks_runner/<package>/<config-hash>/, which holds input.json, output.json, stdout.txt and stderr.txt. The SDK re-runs a hook only when one of these changes:

CBuilder adds its sources to dependencies automatically. If your hook reads other files (a header directory, a config file from a user-define), add them yourself with output.dependencies.add(uri), or the hook won't re-run when they change. This is the output.json of the first example (shortened):

{
  "assets": [
    {
      "encoding": {
        "file": "C:\\...\\.dart_tool\\hooks_runner\\shared\\mathx\\build\\8e04c28b44\\mathx.dll",
        "id": "package:mathx/src/bindings.dart",
        "link_mode": { "type": "dynamic_loading_bundle" }
      },
      "type": "code_assets/code"
    }
  ],
  "dependencies": ["C:\\...\\mathx\\src\\mathx.c"],
  "status": "success"
}

To force a clean rebuild, delete .dart_tool/hooks_runner (or all of .dart_tool and run dart pub get).

Cross-compiling

dart build cli takes --target-os and --target-arch. Hooks get the target in input.config.code, and CBuilder picks a matching cross-compiler. On Windows, building for Linux uses the x86_64-linux-gnu-gcc cross-compiler inside WSL:

dart build cli --target-os=linux --target-arch=x64
Generated: c:\...\mathx\build\cli\linux_x64\bundle\bin\mathx
build/cli/linux_x64/bundle/bin/mathx
build/cli/linux_x64/bundle/lib/libmathx.so

The result runs on Linux (here in WSL Ubuntu):

$ file bin/mathx lib/libmathx.so
bin/mathx:       ELF 64-bit LSB pie executable, x86-64, ... for GNU/Linux 2.6.32, stripped
lib/libmathx.so: ELF 64-bit LSB shared object, x86-64, ... not stripped
$ ./bin/mathx
built with gcc
fnv1a("hello") = 0x4f9f2cab
gcd(1071, 462) = 21

The hook ran a second time with a different config hash, so the Windows and Linux builds are cached side by side. For hooks that download binaries, cross-compiling just means fetching the file for input.config.code.targetOS, which is why the _binaries map above is keyed by target and not by Platform.operatingSystem. Never use dart:io's Platform to make target decisions in a hook: that describes the machine running the build.

Data assets

package:data_assets lets a hook bundle non-code files (JSON, models, fonts):

import 'package:data_assets/data_assets.dart';
import 'package:hooks/hooks.dart';

void main(List<String> args) async {
  await build(args, (input, output) async {
    print('buildDataAssets: ${input.config.buildDataAssets}');
    if (input.config.buildDataAssets) {
      output.assets.data.add(
        DataAsset(
          package: input.packageName,
          name: 'assets/primes.json',
          file: input.packageRoot.resolve('assets/primes.json'),
        ),
      );
    }
  });
}

In Dart 3.13 stable, dart run and dart build only request code assets. The hook's stdout.txt shows:

buildDataAssets: false

Data assets are behind the data-assets experiment, and dart --enable-experiment=data-assets run fails with "this experiment is only available on the main, dev channels". Keep the buildDataAssets check so your hook works both now and when the feature ships, and until then load such files the usual way (see Files and directories).

A package can also have hook/link.dart. Link hooks run after all build hooks, only in dart build (not in dart run or dart test, where input.config.linkingEnabled is false), and they see the whole application. Their main use is shrinking native libraries: the build hook produces a static archive, and the link hook turns it into a shared library that exports only the functions the app calls.

To know what the app calls, annotate the Dart functions with @RecordUse() from package:meta. During dart build the compiler records the calls to annotated functions that are reachable from main and gives the list to link hooks as input.recordedUses. In Dart 3.13 this works on the stable channel. The package needs two more dependencies:

dart pub add meta record_use
// lib/mathx.dart
import 'dart:convert';
import 'dart:ffi';

import 'package:ffi/ffi.dart';
import 'package:meta/meta.dart';

import 'src/bindings.dart';

/// FNV-1a hash of the UTF-8 bytes of [s], computed in C.
@RecordUse()
int fnv1a(String s) {
  final bytes = utf8.encode(s);
  return mathxFnv1a(bytes.address, bytes.length);
}

@RecordUse()
int gcd(int a, int b) => mathxGcd(a, b);

@RecordUse()
String get buildInfo => mathxBuildInfo().toDartString();

CLibrary from native_toolchain_c describes the library once for both hooks:

// lib/src/c_library.dart
import 'package:native_toolchain_c/native_toolchain_c.dart';

/// Shared by hook/build.dart and hook/link.dart.
final cLibrary = CLibrary(
  name: 'mathx',
  assetName: 'src/bindings.dart',
  sources: ['src/mathx.c'],
);

With MSVC, a function marked __declspec(dllexport) is always exported, whatever the linker is told. So the C file lets the build override the macro:

#if defined(MATHX_EXPORT)
/* set by the build */
#elif defined(_WIN32)
#define MATHX_EXPORT __declspec(dllexport)
#else
#define MATHX_EXPORT __attribute__((visibility("default")))
#endif

The build hook clears it only when a link hook will run. In dart run the library from the build hook is used directly and still needs its exports:

// hook/build.dart
import 'package:code_assets/code_assets.dart';
import 'package:hooks/hooks.dart';
import 'package:mathx/src/c_library.dart';

void main(List<String> args) async {
  await build(args, (input, output) async {
    if (!input.config.buildCodeAssets) return;
    await cLibrary.build(
      input: input,
      output: output,
      defines: {
        // When linking is enabled, the link hook decides what is exported,
        // so don't mark functions __declspec(dllexport) in the source.
        if (input.config.linkingEnabled) 'MATHX_EXPORT': '',
      },
    );
  });
}

The link hook maps the recorded Dart functions to C symbols:

// hook/link.dart
import 'package:hooks/hooks.dart';
import 'package:mathx/src/c_library.dart';
import 'package:native_toolchain_c/native_toolchain_c.dart';
import 'package:record_use/record_use.dart';

/// Dart function in lib/mathx.dart -> C symbol it needs.
const _cSymbols = {
  'gcd': 'mathx_gcd',
  'fnv1a': 'mathx_fnv1a',
  'buildInfo': 'mathx_build_info',
};

void main(List<String> args) async {
  await link(args, (input, output) async {
    final uses = input.recordedUses;
    final keep = uses?.calls.keys
        .whereType<Member>()
        .map((m) => _cSymbols[m.name])
        .nonNulls
        .toList();
    print('symbols to keep: $keep');

    await cLibrary.link(
      input: input,
      output: output,
      linkerOptions: LinkerOptions.treeshake(symbolsToKeep: keep),
    );
  });
}

The keys of calls are Method, Getter, Setter or Operator objects. All of them are Members with a name. If you filter with whereType<Method>(), the buildInfo getter is dropped, its C function is removed, and the program fails at run time with Failed to lookup symbol 'mathx_build_info'. If recordedUses is null, keep is null, which tells LinkerOptions.treeshake to keep every symbol.

With a main that calls buildInfo and gcd but not fnv1a, dart build cli prints Running link hooks..., and the hook's stdout.txt contains:

symbols to keep: [mathx_build_info, mathx_gcd]

dumpbin /exports on bundle/lib/mathx.dll lists only those two functions (before the change, all three were exported), and the program works:

          1    0 00001000 mathx_build_info
          2    1 00001010 mathx_gcd
built with MSVC
gcd(1071, 462) = 21

With MSVC, CLinker passes the symbols as a .def file plus /OPT:REF. With gcc or clang on Linux it uses a linker version script and --gc-sections. With native_toolchain_c 0.19.5, the tree-shaking link step failed when cross-compiling to Linux from Windows: the generated linker script has a Windows path that the WSL linker can't open. Run release builds for Linux on Linux until that's fixed.

Security considerations

A build hook is arbitrary Dart code that runs with your user's permissions when you run dart run, dart test or dart build (not on dart pub get). Adding a dependency with a hook is like running its install script.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents