How to create a project with different nested directories

Hello guys, I am trying to create a library and want my project to be structured something like this. How should i approach this? For example I am trying to use the same package everywhere, lets say package testlib but when i try to access any of the


TestLib/
├── core/
│   ├── context.odin    
│   ├── component.odin  
│   └── behavior.odin     
│
├── components/
│   ├── test_component.odin        
│   └── test_component2.odin  
│
└── testlib.odin
// testlib.odin

package testlib

init :: proc() { 
   component_init()
}
// test_component.odin

package testlib

component_init :: proc() {
   println("Test!")
}

and when I am calling the testlib.init() for example I get this.

Error: Undeclared name: component_init component_init()

This is of course some psudo code similar to what I have, but not sure what I am doing wrong and how to approach the separation of the files/packages.

1 Like

In Odin each folder is treated as it’s own package, therefore package name and folders must be the same.

To keep the relative structure of your project, you could use package components in test_component.odin and reference it within testlib.odin using import "components" or import "./components", and then using components.component_init() to call your procedure.

// testlib.odin
package testlib

import "../testlib/components"

main :: proc() {
    components.component_init()
}

// test_component.odin
package components

import "core:fmt"

component_init :: proc() {
   fmt.println("Test!")
}

Thank you, I got it now. A bit similar to how Rust is i guess. Is this good approach of separation for odin, or something else would be better when creating a “library” ?

One more thing, if i want to call the component_init, from outside of the library can i do something like.

testlib.components.component_init() 

Because I will have plenty of functions that are not in the main package testlib and would like them to be callable? If this is not allowed maybe putting everything in same package will be better?

No. Packages are not namespaces, they are just directories. A package means that “every file in this directory is part of the same package”. Sub directories are just that, a separate package, the hierarchy is only for your organisational needs.

package outsidelib

import "path/to/TestLib/components"

main :: proc() {
    components.component_init()
}

That’s false. What’s after package is used in ABI and to make sure all files in a dir are part of the same package, but it is separate from the directory name, like you can’t have a package named “foo-bar” but you can have that name for the dir.

In import baz "./foo-bar" you resolve the directory name by aliasing the path used.

2 Likes

Thanks for clarifying, I missed this point.