Calling matlab from C++

扶醉桌前 提交于 2019-12-28 16:17:12

问题


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!


回答1:


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.




回答2:


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



回答3:


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.




回答4:


You need to tell it which libraries to link against with the -l option to g++. Based on your link line, the library should be in /usr/local/matlabR2010a/extern/lib. As an example, if the library you need is called libmatlab.a you need to to add the -lmatlab option to the command line.



来源:https://stackoverflow.com/questions/7757613/calling-matlab-from-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!