Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling matlab from C++

I tried to call matlab from a .cpp file. I used the following command to compile engdemo.cpp which includes "engine.h"

g++ engdemo.cpp -I/usr/local/matlabR2010a/extern/include -L/usr/local/matlabR2010a/extern/lib -o engdemo

What I got is the following:

engdemo.cpp:(.text+0xdb): undefined reference to `engOpen'
engdemo.cpp:(.text+0x12d): undefined reference to `mxCreateDoubleMatrix'
engdemo.cpp:(.text+0x143): undefined reference to `mxGetPr'
engdemo.cpp:(.text+0x175): undefined reference to `engPutVariable'
engdemo.cpp:(.text+0x189): undefined reference to `engEvalString'

...

collect2: ld returned 1 exit status


I guess it might be some link problem but I am not sure. Please help me out. Many thanks in advance!

like image 852
Lamothy Avatar asked Oct 13 '11 16:10

Lamothy


3 Answers

Following up on what @Kurt S said, you'll need to include libraries. These are common ones you'll need: libeng.lib libmat.lib libmx.lib, but you might need others.

Thus you want to add the linking options -llibeng -llibmat -llibmx

But you might need others as well.

like image 197
Chris A. Avatar answered Oct 04 '22 21:10

Chris A.


Here is a simple makefile to help you get started:

Makefile

# root directory of MATLAB installation
MATLABROOT="/usr/local/matlabR2010a"

all: engdemo

engdemo:
    g++ ${MATLABROOT}/extern/examples/eng_mat/engdemo.cpp -o engdemo \
        -I${MATLABROOT}/extern/include \
        -L${MATLABROOT}/extern/lib -llibeng -llibmx

clean:
    rm -f engdemo *.o

Simply use it by calling make, then running the program as ./engdemo


You can also compile this directly from inside MATLAB. First make sure you have run mbuild -setup command at least once:

>> srcFile = fullfile(matlabroot,'extern','examples','eng_mat','engdemo.cpp');
>> mbuild(srcFile, '-llibeng','-llibmx')
>> !engdemo
like image 30
Amro Avatar answered Oct 04 '22 21:10

Amro


The problem is improper specification of include files and folders (i.e. for libraries and link files) and a few additional dependencies.

You can make use of a simple demo code for the interfacing C/C++ and MATLAB is given here, so as to understand what needs to be done.

Also you need to use a CMAKELISTS.TXT file with suitable settings for MATLAB, for which a good tutorial is available here.

like image 40
Preeti Kaur Avatar answered Oct 04 '22 21:10

Preeti Kaur