Using include in Julia and global variables

Viewed 390

Say I have some Julia module main in a single file "main.jl"

module main

export tester,add
a=1

function hi()
    return "hi"
end

function tester()
    return hi()
end

function add()
    return a+1
end
    
end

Now suppose I want to break up this into two files, with one including auxiliary functions like hi(), like so:

module auxillary

function hi()
    return "hi"
end
end

and use include to copy/paste the functions in auxillary.jl in the main file:

module main

include("auxillary.jl")
export add,tester

a=1

function tester()
    return hi()
end
function add()
    return a+1
end

end

Then calling tester() from main gives an error "hi() not defined". Is include not enough or do I also have to use using?

Secondly, suppose I wanted to move add() to auxillary.jl, but keep the global variable a in main.jl. And then I will call add() from main.jl. How would I do this?

1 Answers

The code layout you need is the following:

module MyModule

# this is equal to do doing `include` here
module Auxillary
function hi()
   return "hi"
end
function add()
   return Main.MyModule.a+1
end
end

export add,tester

using Main.MyModule.Auxillary

a=1
function tester()
   return Auxillary.hi()
end

end

This can be run as:

julia> using Main.MyModule

julia> MyModule.Auxillary.add()
2

julia> MyModule.tester()
"hi"

Explanation

Each module creates its namespace so the trick to get it running is to properly point out which namespace you need. When this code is run in the console, the modele MyModule becomes a submodule of Main and Auxillary is a submodule of MyModule.

Related