# How to autoload user-def functions (in a .m or .nb file)?

How to autoload a few user-def funcions?.

For example the function

emo[x_]:=Module[{a=x},If[x>0,"Happy","Sad"]]


saved in a .nb file or in a .m file

I tried creating in "c:\Program Files\Wolfram Research\Mathematica\11.3\SystemFiles\Autoload" a dir MyFuncs and a subdir MyFuncs/Kernel with init.m whose content is

Get["MyFuncMyFunc"]


Another test was

$$Path=Join[$$Path, {"e:\Users\......\Files\Mathematica11_3"}];


and then

<<MyFunc
<<MyFunc.nb
<<MyFunc.m


I´d like to load a fes user defined functions in an easy and practical way, whitout lot of complications. If it were possible from the files dir.

I was reading a lot of posts but whitout success

• Try using init.m (reference.wolfram.com/language/ref/file/init.m.html) – Rolf Mertig Dec 7 '20 at 14:59
• Also, do not modify anything inside of the installation directory. – Szabolcs Dec 7 '20 at 15:11
• You should run your definitions and save them after into the .mx file by DumpSave["file.mx"]. After this, it can be loaded easily by Get. – Rom38 Dec 7 '20 at 15:44
• @RolfMertig I tried with init.m in several ways, It was not helpful. – Mika Ike Dec 7 '20 at 17:03
• It should work. Where did you put MyFunc.m ? – Simon Woods Dec 7 '20 at 20:43

I also found this not to be straightforward. This is the protocol I eventually adopted;

1. Put your functions in a package e.g. myStuff.m.

BeginPackage["myStuff]

(*functions to be exported go here*)

myFunc1::usage="explain how to use your function here if you wish"

myFunc2::usage="or this can be empty quotes"

Begin["Private"]

(*function definitions, including any private functions go here*)

myFunc1[x_] := Module[{a=0}, If[x>a, Happy, Sad]];

myFunc2[x_] := myPrivateFunc1@x + 1;

myPrivateFunc1[x_] := x^2;

End[]

EndPackage[]

1. You now need to add the path to myStuff.m in a persistent manner.

$Path = Join[$Path,{"C:\\dir1\\dirWhichHasMyStuff"}]

InitializationValue[$Path] =$Path

2. If you use <<myStuff  now, it should work. However, if you want it to be autoloaded, you need to add it as an initialization context.

InitializationValue[\$InitializationContexts] = {"myStuff"}`

(Obviously, if you already have other pre-existing initialization contexts, just add it to the existing list otherwise the old ones will be overwritten.)

The package will automatically be loaded next time you start a kernel.