问题
I'm using Visual Studio 2012 x64 to build and debug a MATLAB 2014a x64 mex file directly (without using the mex
command in MATLAB). I followed the instructions in this question to set up a Visual Studio project named test1
. I followed this tutorial to write a simple mex file, test1.cpp
:
#include <math.h>
#include <matrix.h>
#include <mex.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mexPrintf("Hello World!\n");
}
Building this solution gives me this message:
> 1>------ Build started: Project: test1, Configuration: Debug Win32
> ------ 1> Creating library C:\PROJECTS\matlab\mex\test1\Debug\test1.lib
> and object
> C:\PROJECTS\matlab\mex\test1\Debug\test1.exp
> 1>test1.obj : error LNK2019: unresolved external symbol _mexPrintf
> referenced in function _mexFunction 1>MSVCRTD.lib(crtexe.obj) : error
> LNK2019: unresolved external symbol _main referenced in function
> ___tmainCRTStartup 1>C:\PROJECTS\matlab\mex\test1\Debug\test1.mexw64
> : fatal error LNK1120: 2 unresolved externals
> ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Are there configuration steps I'm missing here? I used the steps in this answer exactly, but maybe it's incomplete for more recent versions of MATLAB?
回答1:
You need to create a Visual Studio project that produces DLLs (as opposed to console or GUI applications). MEX-files are basically shared libraries with a custom extension (*.mexw32
or *.mexw64
on Windows)
The error message indicates that the linker cannot find the entry-point function main()
for an executable, which does not exist for dynamic libraries.
For what it's worth, you can run mex -v ...
in MATLAB, that way it shows you the exact commands used to invoke the compiler and linker.
EDIT:
Step-by-step instructions:
create a new empty VS project to build DLLs (
Visual C++ > Win32 > Win32 console application
then set the type toDLL
in the wizard)Since we're working with MATLAB x64, we need to adjust project configuration to generate 64-bit binaries. From
Build
menu, selectConfiguration Manager
. From the drop-down menu choose<New>
to create a new platform configs, selectx64
and accept.follow the previous instructions you mentioned
add the C/C++ source code for the MEX-file
#include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { plhs[0] = mxCreateString("hello world"); }
switch platform to "x64" in "Release" mode, and build the project. Now you should have a
somefile.mexw64
MEX-file which you can call in MATLAB as a regular function.
来源:https://stackoverflow.com/questions/26220193/building-a-matlab-mex-file-in-visual-studio-gives-lnk2019-unresolved-external-s