dart-setup-ffi-assets
Guides agents in compiling and packaging C/C++ source code into dynamic or static libraries (Code Assets) using Dart's Native Assets hook system (via hook/build.dart and hook/link.dart utilizing package:hooks and package:native_toolchain_c). Use when a user asks to: 'setup native assets', 'compile C/C++ source code', 'bundle dynamic libraries', 'build native C code', 'link native assets', 'implement build.dart or link.dart hooks', or 'integrate C/C++ interop in Dart/Flutter'. Helps agents avoid manual toolchain orchestration and configures secure hash-validated binary downloads or advanced linker tree-shaking with package:record_use mapping.
What this skill does
# Compiling C Code into Code Assets with Native Assets Hooks
Integrate and automate the compilation and packaging of native C/C++ source code into **Code Assets** under Dart's overarching **Native Assets** feature using build and link hooks.
## Contents
- [Introduction](#introduction)
- [Constraints](#constraints)
- [Native Interop Packages](#native-interop-packages)
- [Step-by-Step Workflow](#step-by-step-workflow)
- [Choosing an Integration Approach](#choosing-an-integration-approach)
- [Method 1: Local Compilation with Linker Tree-Shaking (Recommended)](#method-1-local-compilation-with-linker-tree-shaking-recommended)
- [Prerequisite Host Compiler Toolchains](#prerequisite-host-compiler-toolchains)
- [C Source and Bindings Setup](#c-source-and-bindings-setup)
- [Defining the C Library Build Spec](#defining-the-c-library-build-spec)
- [Implementing hook/build.dart](#implementing-hookbuilddart)
- [Implementing hook/link.dart](#implementing-hooklinkdart)
- [Method 2: Downloading Precompiled Dynamic Libraries](#method-2-downloading-precompiled-dynamic-libraries)
- [Why Download Precompiled Binaries?](#why-download-precompiled-binaries)
- [Implementing Precompiled Dynamic Downloads](#implementing-precompiled-dynamic-downloads)
- [Verification Checklist](#verification-checklist)
- [1. Local Execution Sandbox](#1-local-execution-sandbox)
- [2. Verify Target Outputs](#2-verify-target-outputs)
- [3. Verify Tree-Shaking Stripping](#3-verify-tree-shaking-stripping)
- [4. Verify Offline Compliance (User Defines)](#4-verify-offline-compliance-user-defines)
---
## Introduction
Under Dart's **Native Assets** feature, packages can package native code (like C/C++ libraries) as **Code Assets** and bundle them automatically during standard development cycles (e.g., `dart run`, `dart test`, `dart build`, and `flutter run`). The packaging of **Code Assets** is driven by two programmatic hook scripts placed inside a package's `hook/` folder:
1. `hook/build.dart`: Compiles local C sources to machine code or bundles prebuilt native binaries as code assets for a specific host/target architecture.
2. `hook/link.dart`: Links built code assets, applying advanced tree-shaking optimizations to strip unused native symbols and compress the runtime binary size.
---
## Constraints
> [!IMPORTANT]
> Keep all file resolving platform-independent. Never hardcode absolute target paths, shell scripts, or system command variables. Always use `Platform.script.resolve()` or `Uri`-based resolution to ensure scripts are fully portable.
* **Hook Locations**: Compiling and packaging hooks must reside strictly inside the `hook/` directory at the package's root:
* `hook/build.dart` (Build execution phase)
* `hook/link.dart` (Optional packaging/linking/tree-shaking phase)
* **Compile Toolchain Standard**: Use the programmatic APIs from `package:native_toolchain_c` (e.g. `CBuilder` and `CLibrary`) to run compile toolchains. Never invoke raw `gcc`, `clang`, or `msvc` via shell commands.
* **Preamble & License Headers**: Every handcrafted and generated source file (including bindings, helpers, and hooks) must strictly contain the target package's copyright and licensing header.
* **Tree Shaking Mapping**: If utilizing compiler tree-shaking, you must map the target Dart method names (e.g. `Method.name`) back to their raw native C symbol names using a record use mapping generated by FFIgen. The mapping file must reside under `lib/src/third_party/` and strictly use the `.g.dart` extension (e.g., `sqlite3.record_use_mapping.g.dart`).
* **Integrity Safeguards for Precompiled Libraries**: If adopting the dynamic download pattern:
* **Cryptographic Verification**: Downloaded prebuilt binaries must be checked against preconfigured lookup tables containing MD5 or SHA-256 hashes to guarantee binary integrity and prevent tampering.
* **Graceful Recovery**: Support offline developers by providing fallbacks (such as local compiler execution via flags like `local_build`).
---
## Native Interop Packages
Programmatic build and link hooks for **Code Assets** leverage three specialized native interop packages:
| Dependency | Purpose | Key API Abstractions |
| :--- | :--- | :--- |
| **`package:hooks`** | Main orchestrator defining execution bounds. | `build(args, callback)`, `link(args, callback)` |
| **`package:native_toolchain_c`** | Detects local compilers (MSVC, Xcode/Clang, GCC) and executes build toolchains. | `CLibrary`, `CBuilder`, `LinkerOptions.treeshake` |
| **`package:code_assets`** | Models code metadata records passed to dynamic loaders. | `CodeAsset`, `DynamicLoadingBundled` |
---
## Step-by-Step Workflow
### Step 1: Add Dependencies
Add Code Assets hook and toolchain dependencies to your package. You must fetch these dependencies directly from **pub.dev**.
You can add it automatically using the CLI:
```bash
dart pub add code_assets hooks native_toolchain_c record_use dev:ffigen
```
Or manually declare them in your target package's `pubspec.yaml`:
```yaml
dependencies:
code_assets: ^1.0.0
hooks: ^0.1.0
native_toolchain_c: ^0.1.0
record_use: ^0.6.0
dev_dependencies:
ffigen: ^20.1.1
```
### Step 2: Define C Specifications
Define your target C library compilation metadata inside `lib/src/c_library.dart`. This lets both the build and link hooks share a single source of truth for assets, names, and sources.
### Step 3: Implement Build and Link Hook Scripts
Write the compilation orchestration script inside `hook/build.dart` and the dead-code elimination logic inside `hook/link.dart`.
### Step 4: Run the Hook Cycle
Running standard test suites dynamically launches the build and link hook lifecycle in the background:
```bash
dart test
```
---
## Choosing an Integration Approach
There are two primary methods for integrating and delivering C/C++ native assets in Dart. Select the one that matches your project requirements:
| Aspect | Method 1: Local Compilation & Tree-Shaking | Method 2: Precompiled Downloads |
| :--- | :--- | :--- |
| **Primary Use Case** | When C/C++ source code is included directly in the package and you want maximum size optimization. | When compiling locally is slow/complex, or when avoiding developer host toolchain requirements. |
| **Host Toolchain Requirements** | Requires pre-installed platform C compiler (Xcode tools, MSVC, GCC). | Zero compiler setup required on developer/user machines. |
| **Binary Optimization** | Premium. Unused symbols are completely tree-shaken, decreasing library size. | Standard. Standard compiled binaries are shipped as-is. |
| **Offline Setup** | Fully compliant. Works completely offline. | Requires network access to download libraries, with offline fallback. |
---
## Method 1: Local Compilation with Linker Tree-Shaking (Recommended)
In this approach, the build hook invokes local toolchains (GCC, Clang, MSVC) to compile source files directly. The link hook subsequently filters output symbols utilizing compiler options, retaining only target methods invoked in user code. This represents the standard, robust SQLite pattern under `pkgs/code_assets/example/sqlite`.
### Prerequisite Host Compiler Toolchains
Since `package:native_toolchain_c` delegates actual dynamic compilation to the host operating system's default toolchain, the development machine **must** have one of the following compiler packages pre-installed:
* **macOS**: Xcode Command Line Tools. Install via:
```bash
xcode-select --install
```
* **Linux**: GCC or Clang. Install via:
```bash
sudo apt install build-essential
```
* **Windows**: MSVC (Microsoft Visual C++). Install the **Visual Studio Installer** and select the **Desktop development with C++** workload.
*Note: If no compatible toolchain is discovered on the host path, the build hook script will throw a compilation execution exception. Ensure to specify compiler constraints or adopt Method 2 if toolchains cannot beRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.