SV DPI shared library compiled with g++ or gcc

I’m trying various ways to run a C++ function in SystemVerilog. A test example I have is the following:

SV code:

module test;
  import "DPI-C" c2sv_disp = function void c2sv_disp();
  initial
  begin
    c2sv_disp();
  end
endmodule

C code:

#include <stdio.h>
void c2sv_disp() {
  printf("\nHello from C-world!\n");
}

The technique I want to use is with a shared object file. So I compile the C code like this:
gcc -shared -Bsymbolic -fPIC -o test.so test.c

Using Questasim, I run the simulation like this:
vlog test.sv
vsim -sv_lib test.so test

I get the output that I expect from the console:

Hello from C-world!

However, if I compile the code as C++, it doesn’t work. This is how I compile it:
gcc -x c++ -shared -Bsymbolic -fPIC -o test.so test.c

then I run Questasim with:
vlog test.sv
vsim -sv_lib test.so test

now on the console, I get:

** Warning: (vsim-3770) Failed to find user specified function ‘c2sv_disp’ in DPI precompiled library search list "./test.so ".
Time: 0 ps Iteration: 0 Instance: /test File: ./test.sv
** Fatal: (vsim-160) ./test.sv(20): Null foreign function pointer encountered when calling ‘c2sv_disp’

How do I create a shared library file from C++ code that will work with SystemVerilog DPI?

In reply to Gnolaum:

DPI looks for C names, not C++. See https://embeddedartistry.com/blog/2017/4/4/extern-c

Also, most tools will generate this header for you to include. See the vlog -dpiheader option.

In reply to dave_59:

Ok, so I changed my C code to be:


include <stdio.h>
include “test.h” // created from vlog -sv -dpiforceheader -dpiheader test.h test.cpp

extern “C” void c2sv_disp();

void c2sv_disp() {
printf(“\nHello from C-world!\n”);
}


And now it works when I compile with g++

Thanks!