logo

How to Use Functions Defined in Other Files in Julia 📂Julia

How to Use Functions Defined in Other Files in Julia

Overview

Introducing the function include() which executes Julia code itself to use functions from another file. In MATLAB, if it’s in the same directory, it tends to automatically find the function, so some people think this process is hard. There is a way to properly modularize and export, but1 it is not recommended for beginners who urgently need functionality because it is difficult and complicated. It’s not too late to learn about modularization after making a package yourself or when the scale of the program has become unmanageable.

Guide

Let’s say you want to run the baz() function in the foo/bar.jl file from main.jl as shown above. As you can see in the screenshot, you just write Julia code normally without using anything like modules.

Now, the result of the execution by giving the path with include() is as follows.

The reason why 23 is printed as a result of the include() execution is that there was a value assignment like y = 23 at the bottom of the bar.jl file. As you can see, not only functions can be transferred, but also variables, and it’s possible to load data and print logs since it executes the file itself.

Environment

  • OS: Windows
  • julia: v1.8.3