Include, using, export

Hi,

I wish to put experimental code in another file, call “TestFile”, and this file contains a function “TestFunction”. In my Main file called “main.jl”, I wish to access the function “TestFunction”. How do I do it? I tried

include("TestFile.jl")

and get the message “Could not open the file TestFile” or something similar.
What is the easiest approach? Both the file “main.jl” and “TestFile.jl” are in the same directory, and I thought the current directory would automatically be in the LOAD_PATH.

Thanks for any help! I have read the various discussions on the subject.

Please copy and paste the exact error message.
It does sound like the file is not in the right directory. What does pwd() (“print working directory”, i.e. display the current directory) say?

1 Like

I am in the correct directory according to pwd(). I will create an example for you to try.

Consider the file my_test.jl with the code

module myModule
export myTest

function myTest()
    println("inside myTest")
end

myTest()

and my main code, from which I would like to access the “myTest” function:

include("my_module.jl")
using myModule

myModule.my_test
end

Both files are in the same directory, returned by pwd~().
The include statement produces no errors.
“using myModule” produces the error:

ArgumentError: Package myModule not found in current path:

  • Run import Pkg; Pkg.add("myModule") to install the myModule package.
    require(::Module, ::Symbol) at loading.jl:887

I then run in REPL:

] add my_module

and get the error

ERROR: The following package names could not be resolved:

  • my_module (not found in project, manifest or registry)
    Please specify by known name=uuid.

Surely, there must be a way to include files with some mechanism without the need to update lower level machinery (project, manifest, registry)? Thanks.

What is the simplest way to accomplish the task? Thanks.

I think you just need using .myModule. The . is like a local path to indicate you want the local myModule at that path instead of a hypothetical package named myModule.

1 Like

Thank you! I figured it out just before I read the message. My working example code:

include("my_module.jl")
import .myModule: my_test
myTest()
2 Likes