Modules
Every file in the root of a folder is part of the same module. Simple programs don't need to specify module name, in which case it defaults to 'main'.
See symbol visibility, Access modifiers.
Create modules
V is a very modular language. Creating reusable modules is encouraged and is quite easy to do. To create a new module, create a directory with your module's name containing .v files with code:
cd ~/code/modules
mkdir mymodule
vim mymodule/myfile.v
All items inside a module can be used between the files of a module regardless of whether or
not they are prefaced with the pub
keyword.
You can now use mymodule
in your code:
- Module names should be short, under 10 characters.
- Module names must use
snake_case
. - Circular imports are not allowed.
- You can have as many .v files in a module as you want.
- You can create modules anywhere.
- All modules are compiled statically into a single executable.
Special considerations for project folders
For the top level project folder (the one, compiled with v .
), and only
that folder, you can have several .v files, that may be mentioning different modules
with module main
, module abc
etc
This is to ease the prototyping workflow in that folder:
- you can start developing some new project with a single .v file
- split functionality as necessary to different .v files in the same folder
- when that makes logical sense to be further organised, put them into their own directory module.
Note that in ordinary modules, all .v files must start with module name_of_folder
.
init
functions
If you want a module to automatically call some setup/initialization code when it is imported,
you can define a module init
function:
The init
function cannot be public - it will be called automatically by V, just once, no matter
how many times the module was imported in your program. This feature is particularly useful for
initializing a C library.
cleanup
functions
If you want a module to automatically call some cleanup/deinitialization code, when your program
ends, you can define a module cleanup
function:
Just like the init
function, the cleanup
function for a module cannot be public - it will be
called automatically, when your program ends, once per module, even if the module was imported
transitively by other modules several times, in the reverse order of the init calls.