how to make a constant global so all packages files use it?
99 views (last 30 days)
Jan on 23 May 2017
As Stephen has explained already, passing variables as arguments is the best practice.
If you have really good reasons to define a constant globally, do not use global, but prefer a dedicated function, which provides the values as struct:
function C = myPackageConstants()
C.g = 9.81;
C.pi = 3.14159265;
C.VolumeOfHeidelbergBarrel = 221716; % liter
Then call this from all function as:
C = myPackageConstants;
This is less clear than using arguments. If it is called very often, it might matter that it has a certain runtime overhead. But in opposite to globals, you can be sure that the values are not modified anywhere, such that debugging gets horrible.
More Answers (1)
Robert on 26 Feb 2021
You could also define a class with only constant properties. Contrary to Jan's solution, you can access the constants directly, without having to assign all of them to a variable first.
Calling it many times does not result in runtime overhead, like Jan said might be the case for his solution.
g = 9.81
k = 1.234
Reference the constants using:
Of course, if the Constants class is in one of your packages, you have to include its namespace in the call.