matlabmatlab-deploymentmatlab-compiler

Embedding a global variable in standalone Matlab executable?


I'm using mcc to compile my Matlab function(s) into a standalone executable for my target platform. I'd like to be able to reference a global variable that was written into the executable at build time, when running the executable.

For example

  1. At build time, I extract the git commit hash of the repository, commitHash

  2. commitHash somehow becomes a global variable inside my executable

  3. Every output of my executable (a file) is tagged with commitHash

The challenge here is that the commit hash is only known at build time and the standalone executable will no longer be in a repository when it's running.

Thanks!


Solution

  • You can write a MATLAB function that uses system to call the git program and queries the commit ID, and then creates a simple M-file function (commitHash.m) that returns this value, it just writes out the M-file to disk.

    This generated function is used in your code where you want to output your commit ID. The mcc program will include this function in the stand-alone executable's bundle.

    You could write a build script, which simply calls your the function that generates the commitHash.m M-file, and then calls mcc. This ensures that the commitHash.m file is updated every time you build your bundle.


    The M-file generated with the commit ID would be something like this:

    function id = commitHash
    id = '0123456789abcdef';
    

    This is the standard way of creating a constant in MATLAB. In your program you could use it this way:

    fprintf('My program, commit ID: %s\n', commitHash);
    

    The benefit of doing it this way, and not embed the ID in your actual program, is that this way you don't modify code that is in your repository -- committing the change would change the commit ID, which would be weird.

    Add the commitHash.m file to your .gitignore file to prevent it from being committed.