MATLAB: Am I getting an error saying “Error using mex, undefined reference to dlopen” when running a MathWorks Embedded Coder example in Linux

coderdlopenembeddedEmbedded Codererrorldl'librarylinuxmexreferencesharedundefined

I am using MATLAB R2016b and Linux OS with Ubuntu 16.04.2. I am trying to run the Embedded Coder example “Package Generated Code as Shared Libraries”, linked below.
https://www.mathworks.com/help/ecoder/ug/creating-and-using-host-based-shared-libraries.html
I get the following error when I run the example’s script, “run_rtwdemo_shrlib_app.m”.
Error using mex
/tmp/mex_16491860249446_2818/rtwdemo_shrlib_app.o: In function `main':
rtwdemo_shrlib_app.c:(.text+0x1e): undefined reference to `dlopen'
rtwdemo_shrlib_app.c:(.text+0x55): undefined reference to `dlsym'
rtwdemo_shrlib_app.c:(.text+0x67): undefined reference to `dlsym'
rtwdemo_shrlib_app.c:(.text+0x79): undefined reference to `dlsym'
rtwdemo_shrlib_app.c:(.text+0x8c): undefined reference to `dlsym'
rtwdemo_shrlib_app.c:(.text+0x9e): undefined reference to `dlsym'
/tmp/mex_16491860249446_2818/rtwdemo_shrlib_app.o:rtwdemo_shrlib_app.c:(.text+0xb0):
more undefined references to `dlsym' follow
/tmp/mex_16491860249446_2818/rtwdemo_shrlib_app.o: In function `main':
rtwdemo_shrlib_app.c:(.text+0x11c): undefined reference to `dlclose'
collect2: error: ld returned 1 exit status

Best Answer

If you are using the Linux library “dlopen”, the call to the “mex” command must include the -ldl flag. This requirement is generally referenced in lines 73 – 81 of the example’s script, “run_rtwdemo_shrlib_app.m”:
% To incorporate the shared library in a larger project, custom compile and
% link commands may need to be created. The following commented lines gives
% an example of how to create and execute these commands in MATLAB.