简体   繁体   中英

How to get correct function name in shared library?

I want to create shared library in Linux which will be loaded and used by MATLAB. Here is the simple example:

#include "my_code.h"
void multiply_vector(double *x, double b, int N, double* y)
{
  for (int i=0;i<N;i++)
    y[i]=b*x[i];
}

In header file, I simply declare function. Then with CMake I create shared library.

add_library(my_library SHARED my_code.cpp)
install(TARGETS my_library LIBRARY DESTINATION .)

However, when I load this library in MATLAB, by using:

loadlibrary('libmy_library.so','my_code.h')

with warning: "The function 'multiply_vector' was not found in the library in loadlibrary (line 431) ". Indeed, when I try to check content of the shared library with "nm -D" command, I get that function name is changed and see this line:

0000000000000810 T _Z15multiply_vectorPddiS_

Why this happens? How can I get good name of the library function such that it can be called by MATLAB? Thanks!

Names are mangled by default in C++. In order to avoid it, you need to declare your function as extern "C" . Just add the following line before the function definition:

extern "C" void multiply_vector(double *x, double b, int N, double* y);

What extern "C" does is tells the compiler not to mangle the name. So instead of _Z15multiply_vectorPddiS_ it will generate multiply_vector and MATLAB will be able to find it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM