MATLAB: Calling MATLAB from a C++ program in Linux

cengine

Hi there,
I'm trying to call the MATLAB engine from some C++ which I'm writing. I'm using Debian 6.0.4 64 bit. GCC version is 4.4.5-8.
In order to test out what the built in engine can do, I thought a good place to start would be to compile one of the demos which comes with MATLAB (in this case, engdemo.cpp).
I've install csh and when I call g++ engdemo.cpp, these are the errors I get:
% g++ engdemo.cpp
/tmp/ccD4qsD5.o: In function `main':
engdemo.cpp:(.text+0xa8): undefined reference to `engOpen'
engdemo.cpp:(.text+0xf4): undefined reference to `mxCreateDoubleMatrix'
engdemo.cpp:(.text+0x104): undefined reference to `mxGetPr'
engdemo.cpp:(.text+0x12d): undefined reference to `engPutVariable'
engdemo.cpp:(.text+0x13e): undefined reference to `engEvalString'
engdemo.cpp:(.text+0x14f): undefined reference to `engEvalString'
engdemo.cpp:(.text+0x160): undefined reference to `engEvalString'
engdemo.cpp:(.text+0x171): undefined reference to `engEvalString'
engdemo.cpp:(.text+0x182): undefined reference to `engEvalString'
engdemo.cpp:(.text+0x1b1): undefined reference to `mxDestroyArray'
engdemo.cpp:(.text+0x1c2): undefined reference to `engEvalString'
engdemo.cpp:(.text+0x1e1): undefined reference to `engOutputBuffer'
engdemo.cpp:(.text+0x24e): undefined reference to `engEvalString'
engdemo.cpp:(.text+0x282): undefined reference to `engGetVariable'
engdemo.cpp:(.text+0x2aa): undefined reference to `mxGetClassName'
engdemo.cpp:(.text+0x2e2): undefined reference to `mxDestroyArray'
engdemo.cpp:(.text+0x2ee): undefined reference to `engClose'
collect2: ld returned 1 exit status
Now there seem to be a number of guides on the internet explaining how to set it up. Some make mention of makefiles, but I haven't implemented one as it doesn't actually explain what to do.
Any help you can provide would be greatly appreciated!
Many thanks!

Best Answer

gcc/g++ is not able to find MATLAB's header and library files. If compiling from a Linux shell, you will need to add -I, -L, and -l switches (and maybe others) to get a successfully compilation and linkage.
You may find it easier to start by compiling with mex within MATLAB ( starting point for using -f to build engine files). Once that is working, if you really want to compile from the shell, invoke mex with the -v (verbose) flag to learn the exact switches that mex passes down to gcc, and then use those same switches within your shell invocation.