Linker error compiling mex with mingw-w64

ε祈祈猫儿з 提交于 2019-12-01 10:27:12

Take the following configuration file that I'm using (you'll need to adjust the path pointing to MinGW-w64 location accordingly):

mingw_mexopts.bat

@echo off

set MATLAB=%MATLAB%
set MW_TARGET_ARCH=win64
set PATH=C:\MinGW-w64\mingw64\bin;%PATH%

set COMPILER=x86_64-w64-mingw32-g++
set COMPFLAGS=-c -m64 -mwin32 -mdll -Wall -std=c++11 -DMATLAB_MEX_FILE
set OPTIMFLAGS=-DNDEBUG -O2
set DEBUGFLAGS=-g
set NAME_OBJECT=-o

set LINKER=x86_64-w64-mingw32-g++
set LINKFLAGS=-shared -L"%MATLAB%\extern\lib\win64\microsoft" -L"%MATLAB%\bin\win64"
set LINKFLAGSPOST=-lmx -lmex -lmat
set LINKOPTIMFLAGS=-O2
set LINKDEBUGFLAGS=-g
set LINK_FILE=
set LINK_LIB=
set NAME_OUTPUT=-o "%OUTDIR%%MEX_NAME%%MEX_EXT%"

Next here is a simple MEX-function that uses C++11 threads:

test.cpp

#include "mex.h"
#include <vector>
#include <thread>

void say_hello(int tid) {
    mexPrintf("hello from %d\n", tid);
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    std::vector<std::thread> threads;
    for (int i=0; i<10; i++) {
        threads.push_back(std::thread(say_hello, i));
    }        
    for(auto& t : threads) {
        t.join();
    }
}

Finally we compile and run it in MATLAB:

>> mex -f mingw_mexopts.bat -largeArrayDims test.cpp

>> setenv('PATH', ['C:\MinGW-w64\mingw64\bin;', getenv('PATH')])

>> test
hello from 0
hello from 4
hello from 2
hello from 3
hello from 5
hello from 1
hello from 6
hello from 8
hello from 7
hello from 9

Note that if you're going to deploy this to another machine, you'll have to also copy a few dependent DLL's (you'll find them in MinGW bin folder), and place them next to the MEX-file. Use Dependency Walker to list them. In my case it was:

  • libstdc++-6.dll
  • libgcc_s_seh-1.dll
  • libwinpthread-1.dll

I am using GCC 4.8.2 with MATLAB R2014a running on 64-bit Windows.

Note these error messages:

C:\Users\Bas\AppData\Local\Temp\cc4hwD3A.o:Gomoku_mex.cpp:(.text+0x9d1c): undefined reference to `mxGetPr' 
C:\Users\Bas\AppData\Local\Temp\cc4hwD3A.o:Gomoku_mex.cpp:(.text+0x9d83): undefined reference to `mxCreateDoubleScalar'

The library search path for libmex, libmx, libmat, ... is not added in your link command. The directory in your script is the bin directory containing DLLs. That's not correct here.

LINKFLAGS  =  -shared mex.def -L"C:\Program Files\MATLAB\R2013a\extern\lib\win64\microsoft" -static-libstdc++ 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!