首页 > 解决方案 > 将 GSL 库链接到 Matlab MEX 时如何修复“未知类型名称”错误

问题描述

我目前正在尝试优化我在 MATLAB(版本 R2019a)中处理的一些代码。为了计算我的结果,MATLAB 必须多次计算某个函数,从而减慢一切速度。因此,我认为用 C 语言编写这个函数并将其导入 MATLAB 会大大加快速度。不幸的是,我尝试使用 MEX 将 C 代码编译到 MATLAB 中遇到了一些麻烦。

我以前用过 C,但肯定不是专家。无论如何,我已经在 C 中测试了代码并且它可以工作,问题在于尝试在 MATLAB 中编译代码。我正在使用 GNU 科学库 (GSL),因此应该在 MATLAB 中使用 MEX 编译这些库。

以下是导致相同问题和错误的最小工作示例。C 代码看起来像这样,保存在MWE.c

#include "mex.h" // The mex library
#include <gsl/gsl_sf_bessel.h> // GSL function

// Define some function, in my case this is somewhat more complicated
double bessel_fun (double *x)
{
    return gsl_sf_bessel_J0 (*x);
}

// MEX function needed for compiling in MATLAB
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    //declare variables
    mxArray *x_M, *y_M;
    double *x, *y;

    //associate inputs
    x_M = mxDuplicateArray(prhs[0]);

    //associate outputs
    y_M = plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);

    // Access variables
    x = mxGetPr(x_M);
    y = mxGetPr(y_M);

    // Save the result in the output variable
    y[0]=bessel_fun(x);
}

然后我在 MATLAB 中使用

    mex -IC:/MinGW/include -LC:/MinGW/lib -lgsl -lgslcblas MWE.c

MATLAB 没有编译(如果我使用包含任何库的 C 代码,它确实有效),而是返回很多错误,如下所示:

Error using mex
In file included from
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/x86_64-w64-mingw32/include/stddef.h:7:0,
                 from
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/lib/gcc/x86_64-w64-mingw32/6.3.0/include/stddef.h:1,
                 from C:\MinGW\include/stdio.h:68,
                 from C:\Program Files\MATLAB\R2019a/extern/include/mex.h:38,
                 from C:\userpath\MWE.c:1:
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/x86_64-w64-mingw32/include/crtdefs.h:35:19:
error: expected '=', ',', ';', 'asm' or '__attribute__' before 'typedef'
 __MINGW_EXTENSION typedef unsigned __int64 size_t;
                   ^~~~~~~
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/x86_64-w64-mingw32/include/crtdefs.h:45:19:
error: expected '=', ',', ';', 'asm' or '__attribute__' before 'typedef'
 __MINGW_EXTENSION typedef __int64 ssize_t;
                   ^~~~~~~
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/x86_64-w64-mingw32/include/crtdefs.h:52:9:
error: unknown type name 'size_t'
 typedef size_t rsize_t;

[...]

以及不同类型名称的相同错误。

有谁知道在 MATLAB 中使用 MEX 编译时如何正确包含库?

标签: cmatlabmexgsl

解决方案


明白了。请您尝试以下方法:

mex -U__MINGW_EXTENSION -IC:/MinGW/include -LC:/MinGW/lib -lgsl -lgslcblas MWE.c

推荐阅读