It seems using a module can be done at arbitrary places within source files, even in conditional blocks, without too much trouble, except for when a module provides a macro that you would otherwise use. For example, this will not work:
paulm@cmstorm 15:27:~$ cat fail.jl
if false
using Profile
@profile main()
end
paulm@cmstorm 15:27:~$ julia fail.jl
ERROR: LoadError: LoadError: UndefVarError: @profile not defined
in expression starting at /home/paulm/fail.jl:3
in expression starting at /home/paulm/fail.jl:1
I assume the compiler wants/needs to do macro expansion, even though the code block obviously will never get executed.
One workaround here would be to manually expand @profile, which is quite small. But this would get annoying (and error prone, especially over time) for larger macros. Any other tricks to conditionally use a module and its macros like this?
Well, that indeed works for the false case. But I just noticed that the true case doesn’t work anyway:
melis@juggle 17:38:~$ cat t.jl
if true
using Profile
@profile main()
end
melis@juggle 17:38:~$ julia t.jl
ERROR: LoadError: LoadError: UndefVarError: @profile not defined
in expression starting at /home/melis/t.jl:3
in expression starting at /home/melis/t.jl:1
This fails for the same reason stated here, you need to split this into 2 “@static if…” clauses so the import is resolved before the macro is expanded