Modules
Split a program across files and import reusable public functions.
Core concepts
import, pub fn, local module, project layout
How the learner should approach this project
Do not paste the complete program immediately. Create the file, type the first step, run vpp check, and then run the program when a complete entry point exists. Read the explanation before looking at the snippet. After each step, predict what the new code should do. This turns the page into a lesson rather than a code dump.
Step 1: Create the module file
A module contains reusable definitions. Functions intended for another file must be public. The module example uses a small math file that exports add and mul.
After typing the snippet, identify the new names introduced by the step. Ask what each name represents, what type the compiler should infer or check, and what value should exist after the code runs.
pub fn add(a: int, b: int) -> int {
return a + b
}
pub fn mul(a: int, b: int) -> int {
return a * b
}Step 2: Import and call the module
Imports appear before functions and types. Once math.vpp is imported, the exported functions are available to main.
The compiler resolves the local module path as part of the project.
Before moving forward, explain how this step connects to the previous one. In particular, identify which values cross a function boundary, which values change, and which values are guaranteed by the type system.
import "math.vpp"
fn main() -> int {
let sum = add(10, 5)
let product = mul(sum, 2)
print(sum)
print(product)
return 0
}Complete source
Main file main.vpp:
import "math.vpp" fn main() -> int { let sum = add(10, 5) let product = mul(sum, 2) print(sum) print(product) return 0 }
pub fn add(a: int, b: int) -> int {
return a + b
}
pub fn mul(a: int, b: int) -> int {
return a * b
}Expected behavior
The complete program should produce the following output when run with the command shown below. Exact formatting should follow the current V++ runtime.
15 30
Run the project
cd projects/14-modules && vpp run main.vpp
What the learner should understand after this project
Modules separate code into files and make public APIs explicit. Imports become the connection between reusable code and the application entry point.
Common mistakes to teach
- Importing after a function declaration
- Forgetting pub on a function that must be visible outside the module
- Running the command from the wrong project directory
Practice extension
Add a subtract function to math.vpp, export it, import it through main, and call it.
A strong learner should be able to explain the program without looking at the code, rebuild the core idea from memory, and make the practice change without copying a solution.
Full program
pub fn add(a: int, b: int) -> int {
return a + b
}
pub fn mul(a: int, b: int) -> int {
return a * b
}