Main Content

mexAtExit (C and Fortran)

Register function to call when MEX function clears or MATLAB terminates

C Syntax

#include "mex.h"
int mexAtExit(void (*ExitFcn)(void));

Fortran Syntax

#include "fintrf.h"
integer*4 mexAtExit(ExitFcn)
subroutine ExitFcn()


Use mexAtExit to register a function to call just before clearing the MEX function or terminating MATLAB®. mexAtExit gives your MEX function a chance to perform tasks such as freeing persistent memory and closing files. Other typical tasks include closing streams or sockets.

Each MEX function can register only one active exit function at a time. If you call mexAtExit more than once, then MATLAB uses the ExitFcn from the more recent mexAtExit call as the exit function.

If a MEX function is locked, then you cannot clear the MEX file. Therefore, if you attempt to clear a locked MEX file, then MATLAB does not call the ExitFcn.

In Fortran, declare the ExitFcn as external in the Fortran routine that calls mexAtExit if it is not within the scope of the file.


In C MEX files, throwing an exception in ExitFcn causes MATLAB to crash.

Input Arguments

expand all

Function to run on exit, specified as a pointer.

Output Arguments

expand all

Always returns 0.


See these examples in matlabroot/extern/examples/mex:

Version History

Introduced before R2006a