My folder contains several files, which are compiled in this order: global.ml, zone.ml, abs.ml, main.ml
global.ml contains some reference variables (e.g. let g1 = ref 0) for all the files.
In zone.ml there is a declaration let f = !g1.
In abs.ml, there is g1 := 5, which will be run by main in the beginning of run-time, I consider it as an initialization of g1 given the real run-time context.
Later main will call Zone.f. Curiously, what I realize is that it takes f = 0 instead of f = 5.
Do you think this behavior is normal? If so, what should I change, to make it take the current value of !g1 into account?
PS: Maybe one solution is to make a function let f v = v in zone.ml then let main call Zone.f !g1. But I have several global reference variables as g1 in global.ml, I hope they could be valid over all the files and functions, and I don’t want to get them involved in the signature of a function.
You are basically concerned with the order of evaluation of the top-level values in your modules. The order in which this happens isn’t related to the order that you compile the files, but rather the order that they appear when you link the files.
If you ignore the module boundaries, if you link the files in the order you give, what you have is like this:
It shouldn’t be surprising that
fhas the value 0.Note that your
mainis not necessarily the first thing that happens at runtime. Top-level values are evaluated in the order the files appear when you link them. Very commonly,mainis the last top-level thing to happen (because its file is usually the last one).(Also note that having a
mainat all is just a convention, presumably adopted by former C programmers like me. There’s no requirement to have a function namedmain. OCaml just evaluates the top-level values in order.)Edit:
It’s difficult to say how to restructure your code without knowing more about it. The essence of your problem appears to be that you define
fas a top-level immutable value inzone.mlbut you want its value to followg1, which is a mutable value.The simplest suggestion would be to remove the definition of
ffromzone.mland replace it everywhere in the file with!g1.If you want to retain the name
fat the top level inzone.ml, you have to redefine it as something other than an immutable value. A function is the most obvious choice:Then you would replace uses of
finzone.mlbyf ()instead.