Multiple files per module

question

#1

I want to split a module into multiple files. Should I put the module declaration:

module MyModuleName
...
end   # module

in all the files?


#2

You should have a single file with the module declaration and include("file.jl") inside it for each file you need. You can think of include as the equivalent of copy and pasting the contents of the included files into the place they were included (edit: not quite right, see below).


#3

Thanks.


#4

This is not quite right. Expressions in an included file are evaluated in the global scope of the current module. So inclusion works as expected for defining types and top-level functions, but not for local variable bindings. (The documentation is a bit misleading.)

Example: if file “h1.jl” has

a=3

then

julia> let b=4
       include("h1.jl")
       global f
       f(x) = a+b*x
       end
f (generic function with 1 method)

julia> b
ERROR: UndefVarError: b not defined

julia> a
3

and you get all the “benefits” of global variables:

julia> @code_typed(f(4))
CodeInfo(:(begin 
        return Main.a + (Base.mul_int)($(QuoteNode(4)), x)::Int64
    end))=>Any