I am programming in ChucK programming language. I want to use a class declared in another file.
I have declared a public class called Foo
in a file called foo.ck
. Then I have added the file foo.ck
in another file and tried to use the class. I have got this error:
[using_foo.ck]:line(2): undefined type 'Foo'...
[using_foo.ck]:line(2): ... in declaration ...
The file with the class (foo.ck
):
public class Foo {}
Foo foo;
The file trying to use Foo
(using_foo.ck
):
Machine.add("foo.ck");
Foo foo;
The file foo.ck
with the class Foo
works if I run it standalone, but I cannot use the class from another file.
Chuck version:
chuck version: 1.5.0.0 (chai)
linux (pulse) : 64-bit
I have found the problem. The class must be visible at compile time. When ChucK tries to compile using_foo.ck
, it has not already run foo.ck
. So it does not know the class Foo
. The class is not visible. The function Machine.add
is only run at execution time. In this case, it will not be run at all, because this script will not compile because the class Foo
is not visible at compile time.
The solution is to run the file with the class (foo.ck
) before the file using the class (using_foo.ck
). There are two ways of doing it. In both ways, the line that is loading foo.ck
(Machine.add("foo.ck");
) must be removed, otherwise the file foo.ck
will be loaded twice.
First way: run ChucK passing both files as arguments. The file with the class definition must come before the file using the class:
$ chuck foo.ck using_foo.ck
Second way: use a third file that adds both files. The file with the class definition must be added before the file using the class. Say the third file is called init.ck
. Its code should be:
Machine.add("foo.ck");
Machine.add("using_foo.ck");
Then the command is:
$ chuck init.ck