c++ - 尝试使用 header 从 C++ 访问 matlab

标签 c++ matlab gcc linker matlab-engine

我正在尝试编译一个包含 Matlab 提供的引擎头文件的 C++ 程序。文件 MLP.cpp 包含:

#include <engine.h>
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

并引用了以下错误中突出显示的 matlab 函数。运行时:

g++ -c MLP.cpp -I/usr/local/matlab/extern/include -L/usr/local/matlab/extern/lib -llibeng -llibmx -lmatlab
g++ MLP.o -o main

我收到以下错误:

MLP.o: In function `MatLabPredictor::MatLabPredictor(char*)': 

MLP.cpp:(.text+0x18): undefined reference to `engOpen'

MLP.cpp:(.text+0x36): undefined reference to `engEvalString'

MLP.cpp:(.text+0x4a): undefined reference to `engEvalString'

MLP.cpp:(.text+0x5e): undefined reference to `mxCreateDoubleMatrix'

MLP.cpp:(.text+0x79): undefined reference to `mxGetPr'

MLP.o: In function `MatLabPredictor::~MatLabPredictor()':

MLP.cpp:(.text+0xa1): undefined reference to `engClose'

MLP.o: In function `MatLabPredictor::retrain(double)':

MLP.cpp:(.text+0x104): undefined reference to `engPutVariable'

MLP.cpp:(.text+0x118): undefined reference to `engEvalString'

MLP.cpp:(.text+0x12c): undefined reference to `engEvalString'

MLP.cpp:(.text+0x140): undefined reference to `engEvalString'

MLP.o: In function `MatLabPredictor::predict_next_value()':

MLP.cpp:(.text+0x162): undefined reference to `engEvalString'

MLP.cpp:(.text+0x176): undefined reference to `engGetVariable'

MLP.cpp:(.text+0x186): undefined reference to `mxGetData'

MLP.cpp:(.text+0x199): undefined reference to `mxDestroyArray'
collect2: ld returned 1 exit status

我还尝试将编译命令更改为:

g++ -c MLP.cpp -I/usr/local/matlab/extern/include -L/usr/local/matlab/bin/glnxa64 -llibeng -llibmx -lmatlab
g++ MLP.o -o main

最佳答案

您指定的第一个 g++ 命令用于编译,为此您只需要 -I 选项。为它指定 engine.h 所在文件夹的路径(-I$MATLABROOT/extern/include - 假设 MATLABROOT 指向 Matlab 的根目录安装,在本例中为 /usr/local/matlab)。

第二个 g++ 命令用于链接,您需要将 -L 和 -l(s) 放在那里。就像是 -L$MATLABROOT/bin/glnxa64 -leng -lmx

所以我们最终得到这个序列:

g++ -c MLP.cpp -I$MATLABROOT/extern/include

g++ MLP.o -o main -L$MATLABROOT/bin/glnxa64 -leng -lmx

为了获得相同的结果,但在一行中:

g++ MLP.c -o main -I$MATLABROOT/extern/include -L$MATLABROOT/bin/glnxa64 -leng -lmx

注意:libeng.solibmx.so 必须在您要运行此可执行文件时可以访问,因此扩展 LD_LIBRARY_PATHPATH 文件夹:$MATLABROOT/bin/glnxa64,然后再尝试运行 main

关于c++ - 尝试使用 header 从 C++ 访问 matlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19966083/

相关文章:

c - 让我发疯的 Pthread 数据竞赛

c++ - 具有 shared_ptr vector 的类的析构函数导致错误

matlab - 在MATLAB中使用randi获取随机值: values are not distributed uniformly

matlab - 为 sublime 设置默认语法不起作用

python - 安装 scikit : gcc-4. 2 未找到,使用 Clang 代替

c++ - 为什么模板中的 static_assert 使用等效表达式会给我不同的结果?

c++ - 无法将 tomsfastmath 链接到 libtomcrypt

c++ - 预置和附加到 cstring

c++ - 如何初始化不同对象指针的 vector ?

python - 使用 python 读取大型文本文件比使用 Matlab 读取相同文本的相同代码慢得多,知道为什么吗?