Suppose I have three octave scripts a.m, b.m, c.m
, and two global variables x, y
. Is it possible to define these global variables in such a way that they can be shared across scripts? For example in a separate include file?
More Generally, how do global variables in GNU octave work?
A global variable is accessible to all functions in every source file where it is declared. To avoid problems: Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error.
The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.
A variable is declared global by using a global declaration statement. The following statements are all global declarations. Note that the global qualifier extends only to the next end-of-statement indicator which could be a comma (' , '), semicolon (' ; '), or newline (' '\n' ').
A variable or function can be declared any number of times, but it can be defined only once. (Remember the basic principle that you can't have two locations of the same variable or function).
It seems you have to declare the variable global, and you also have to explicitly tell Octave that the variable you are referencing is in a different (global) scope.
in library.m
global x = 1;
in main.m
function ret = foo()
global x;
5 * x;
endfunction
foo() should return 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With