Julia: Split module into multiple files

I copied this question from StackOverflow. I was not sure if I would get answers there, or if it is better to ask here. Link: Julia: Split module into multiple files - Stack Overflow :

I am using Julia v0.6.4. Consider the following module, saved in FooModule.jl:

module FooModule

export Foo
export doSomething

mutable struct Foo
    x::Int64
    function Foo(xin::Int64)
        new(xin)
    end # Foo
end # struct

function doSomething(F::Foo)
    println(F.x+123)
end # doSomething

end # module

And a main.jl:

using FooModule
function main()
F = Foo(10)
doSomething(F)
end # main

Now I start the Julia REPL:

julia> include("main.jl");

julia> main()
133

I.e. I get what I expect.
Now imagine doSomething contains many lines and I want to split FooModule.jl. I would like to do something like this:

module FooModule

export Foo
export doSomething

include("doSomething.jl")        # <- include instead of writing out

mutable struct Foo
    x::Int64
    function Foo(xin::Int64)
        new(xin)
    end # Foo
end # struct

end # module

and doSomething.jl

function doSomething(F::Foo)
    println(F.x+123)
end # doSomething

This gives an error since doSomething.jl knows nothing about Foo.

julia> include("main.jl");
ERROR: LoadError: LoadError: LoadError: UndefVarError: Foo not defined
Stacktrace:
 [1] include_from_node1(::String) at ./loading.jl:576
 [2] include(::String) at ./sysimg.jl:14
 [3] include_from_node1(::String) at ./loading.jl:576
 [4] eval(::Module, ::Any) at ./boot.jl:235
 [5] _require(::Symbol) at ./loading.jl:490
 [6] require(::Symbol) at ./loading.jl:405
 [7] include_from_node1(::String) at ./loading.jl:576
 [8] include(::String) at ./sysimg.jl:14
while loading ~/Desktop/doSomething.jl, in expression starting on line 1
while loading ~/Desktop/FooModule.jl, in expression starting on line 6
while loading ~/Desktop/main.jl, in expression starting on line 1

How can I resolve this problem?

Put the include after the struct definition? It’s pretty typical for modules to have several includes (you might put the struct in a separate file too and include that as well), but order matters. You can’t reference something before it’s defined.

2 Likes

You already got an answer on SO, and you even accepted it long before re-posting the question here. Was there something that needed clarification? Would be good to update the answer there too if that’s the case.

2 Likes