Julia call c++, could not load symbol

In the debug.cpp:

#include <stdio.h>
// g++ -shared -fPIC -o debug.so debug.cpp

void show(int *a) {
    for (int i = 0; i < 10; i++) {
        printf("a[%d] = %d\n", i, a[i]);
    }
}

void hello() {
    printf("hello world");
}

Then compiled by the following command:
g++ -shared -fPIC -o debug.so debug.cpp

When calling from Julia, I get the error could not load symbol show:

using Libdl

lib = "./debug.so"
a = ones(Cint, 10)
ccall((:show, lib), Cvoid,
  (Ptr{Cint},), a)
ERROR: LoadError: could not load symbol "show":
./debug.so: undefined symbol: show
Stacktrace:
 [1] top-level scope

The C++ compiler will mangle that name. When I run nm debug.so, I see something like:

0000000000003f30 T __Z4showPi
0000000000003f80 T __Z5hellov
                 U _printf

You need to use extern "C" to have C++ create a symbol that is C compatible. Just add this:

extern "C" {
void show(int*);
}

See: What is the effect of extern "C" in C++? - Stack Overflow

4 Likes

Awesome, it works. :clap: