FindMatlab: add support in matlab_add_mex to not link all the found MATLAB libraries
As of CMake 3.20, the matlab_add_mex
CMake command provided by the FindMatlab
CMake module always links all the libraries found in the system out of the following four ones:
Matlab_MEX_LIBRARY
Matlab_MX_LIBRARY
Matlab_ENGINE_LIBRARY
Matlab_DATAARRAY_LIBRARY
This strategy of always link everything works fine if the generated mex library is used in the same machine, but can create problems if a a mex library is not using one of this libraries, and then is deployed on a system without such libraries.
More in particular, I am currently compiling some mex libraries with matlab_add_mex
that do not use Matlab_ENGINE_LIBRARY
, and that at the moment can't be loaded when deployed on MATLAB Online
as of 2021/03/10 on MATLAB Online Matlab_ENGINE_LIBRARY
is not installed. See https://github.com/robotology/robotology-superbuild/issues/653 for the downstream issue.
The most obvious and scalable solution for this that I can think of is to add a NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES
to matlab_add_mex
, that disables automatic link to MATLAB libraries in matlab_add_mex
, and let the user directly link the libraries that are needed via the LINK_TO
option (or via external target_link_libraries
).
The way to use it would be change some like (real world code adapted from https://github.com/robotology/blockfactory/blob/fe2c6369f73a3cf0a300297989e7c6c536df198f/sources/Simulink/CMakeLists.txt#L6):
matlab_add_mex(
NAME MexLibrary
OUTPUT_NAME BlockFactory
SRC src/SimulinkBlockInformation.cpp
src/SimulinkBlockInformationImpl.cpp
src/BlockFactory.cpp
LINK_TO BlockFactory::Core shlibpp::shlibpp mxpp)
to
matlab_add_mex(
NAME MexLibrary
OUTPUT_NAME BlockFactory
SRC src/SimulinkBlockInformation.cpp
src/SimulinkBlockInformationImpl.cpp
src/BlockFactory.cpp
NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES
LINK_TO ${Matlab_MEX_LIBRARY} ${Matlab_MX_LIBRARY} BlockFactory::Core shlibpp::shlibpp mxpp)
If there are no objections (cc @brad.king @nfogh @raffienficiaud) I would be happy to open a MR for this change.