Learn · 12

Modules & Imports

Organize multi-file Ochre projects using relative import statements, cycle detection, and ochre.toml project scaffolding.

As programs grow beyond a single script, splitting code into focused .och modules keeps functions, structs, and tests easy to navigate.

Importing Local Files

Use import "./relative/path.och" at the top of a file. Ochre resolves paths relative to the importing file's directory, merges top-level definitions in dependency order, and automatically prevents duplicate loading or circular import infinite loops.

Example: math_lib.och

fn square(x: Int) -> Int {
    return x * x
}

fn cube(x: Int) -> Int {
    return x * x * x
}

Example: main.och

import "./math_lib.och"

fn main() {
    println("5^2 = {square(5)}")
    println("3^3 = {cube(3)}")
}

Run ochre main.och from your terminal and you will see:

5^2 = 25
3^3 = 27

Project Layout with ochre init

Running ochre init my-app creates a clean project skeleton:

my-app/
├── ochre.toml
└── src/
    └── main.och

You can place helper modules alongside src/main.och (for example src/routes.och, src/models.och) and import them with import "./routes.och".

Common Mistake: Missing File Path Extension or Non-String Import

The import keyword requires a string path ("..." or '...'):

import math_lib

The parser reports: expected string path after 'import' with help: example: import "./math.och".

Exercise

In a local directory, create greeter.och defining fn welcome(name: Str) -> Str, import it from app.och with import "./greeter.och", and run ochre app.och.

Show Solution

greeter.och:

fn welcome(name: Str) -> Str {
    return "Welcome to Ochre, {name}!"
}

app.och:

import "./greeter.och"

fn main() {
    println(welcome("Ada"))
}