I have a shared library `libsharedlib.so' which used to be generated from C files. Since the library now needs to use functions from a 3rd party C++ library, I would like to convert my shared library from C to C++ (the code is relatively simple). Based on the differences I read here, the only adaptations I had to do were in my use of stdlib and stdio functions. The headers were changed from
#include <stdio.h>
#include <stlib.h>
To
#include <cstdlib>
#include <cstdio>
And all calls to the functions in these libraries are prefixed with the std::
namespace (e.g. std::malloc
instead of malloc
, I did not use using namespace std
). The source file extensions were changed from .c to .cpp. I also had to add newlines at the end of each file, and had to cast my malloc
's. No other compiler feedback after that. The shared library is compiled with the following command:
pgcpp -shared -I./inc/ -o ./lib/libsharedlib.so file1.cpp file2.cpp ...
And returns no errors or warnings.
I now have a MEX function, mex_gateway.cpp
which calls functions from this library:
#include "sharedlibraryheader.h"
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]){
...
function_from_library(data);
}
It is compiled with the following command
mex -L./lib/ -lsharedlib -I./inc/ mex_gateway.cpp
Which (when adding the verbose flag -v
) actually executes the following commands:
g++ -c -I./inc/ -I/opt/MATLAB/R2013b/extern/include -I/opt/MATLAB/R2013b/simulink/include -DMATLAB_MEX_FILE -ansi -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread -DMX_COMPAT_32 -O -DNDEBUG "mex_gateway.cpp"
g++ -O -pthread -shared -Wl,--version-script,/opt/MATLAB/R2013b/extern/lib/glnxa64/mexFunction.map -Wl,--no-undefined -o "mex_gateway.mexa64" mex_gateway.o -L./lib/ -lsharedlib -Wl,-rpath-link,/opt/MATLAB/R2013b/bin/glnxa64 -L/opt/MATLAB/R2013b/bin/glnxa64 -lmx -lmex -lmat -lm
I get the following error:
mex_gateway.o: In function `mexFunction':
mex_gateway.cpp:(.text+0x24e): undefined reference to `function_from_library(...arguments...)'
collect2: ld returned 1 exit status
mex: link of ' "mex_gateway.mexa64"' failed.
Of course, I triple-checked the build commands which have the right path to the shared library and the library name. The shared library does have the definition of the function:
[user@machine]$ nm lib/libsharedlib.so | grep function_from_library
000000000000198a t __function_from_library__FPCdN51dN27iiiiPdPdPdPdPdPdEND
0000000000001360 T function_from_library__FPCdN51dN27iiiiPdPdPdPdPdPd
So where's the problem?
EDIT: My sharedlibraryheader.h
file looks like this:
#ifndef __SHAREDLIBRARYHEADER_H__
#define __SHAREDLIBRARYHEADER_H__
#ifdef _cplusplus
extern "C"{
#endif
int function1 ( ... );
...
void function_from_library( ... );
...
#ifdef _cplusplus
}
#endif
#endif