Reputation: 839
I am trying to build a mex function in MATLAB. The function depends on a C++ library. However, I get unresolved externals in MATLAB no matter what I do. I have created three trivial files to demonstrate the problem:
my_test123.h
_declspec(dllexport) void my_test();
my_test.cpp
extern "C" {
#include "my_test123.h"
}
void my_test() {
}
I compile and link the two files above using the command:
cl /LD /Femy_test.dll my_test.cpp
This generates two files, my_test.lib and my_test.dll.
The third file is a trivial mexfunction:
my_mex.cpp
#include "mex.h"
extern "C" {
void my_test();
}
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
my_test();
}
In MATLAB, I use the command below:
mex -v my_mex.cpp my_test.lib
I also tried:
mex -v my_mex.cpp -lmy_test.lib
All files are in the same directory and the mex command is finding the .lib file (if I try a random name instead of my_test.lib , I get a file not found error).
The error I get is:
Error using mex Creating library my_mex.lib and object my_mex.exp my_mex.obj : error LNK2019: unresolved external symbol my_test referenced in function mexFunction my_mex.mexw64 : fatal error LNK1120: 1 unresolved externals
I have also tried making every file a C file (removing the externs and changing the mexfunciton extension to .c) and compiling in C. But I get the same exact error.
I am using Visual Studio 2013 and 64 bit version of MATLAB 2014b.
Any help is much appreciated.
Upvotes: 1
Views: 1356
Reputation: 839
After many hours working on this and help from the MathWorks support line, I discovered the following:
You need to take several factors into account:
Let's assume the .dll is a 32 bit .dll and MATLAB is 32 bits
mex function has an extension .cpp, .dll is a C++ .dll You don't need to add any extern "C" neither in my_test.cpp or in my_mex.cpp.
mex function has an extension .c, .dll is a C++ .dll You need to add "extern "C"* in my_test.cpp.
mex function has an extension .cpp, .dll is a C .dll You don't need to add extern "C" to my_test.cpp but you need one in my_mex.cpp.
mex function has an extension .c, .dll is a C .dll You don't need to add any extern "C" neither in my_test.cpp or in my_mex.cpp.
It looks like depending on the extension of the mex function file, MATLAB compiles it as a C or a C++ file. Knowing this, the extern usage should make sense.
All the above is still valid but for a 64 bit MATLAB but you need a 64 bit dll.
Upvotes: 2