1

lib.c contains:

#include <stdio.h>
void testFunction()
{
    printf("This is the testFunction from lib.so");
}

I compiled file with this command:

g++ -fPIC -shared lib.c -o lib.so

After I runned nm on lib.so I found that testFunction became _Z12testFunctionv. Why? I think this is a big problem when it comes to load functions with dlsym.

Tavy
  • 861
  • 11
  • 15

2 Answers2

4

You compiled a C program with the C++ compiler g++ (and your small C code happens to be valid C++ code). So you observe some name mangling. You should use gcc instead (it is part of the same compiler suite GCC....):

 gcc -Wall -g -O -fPIC -shared lib.c -o lib.so

(I strongly recommend compiling with -Wall to get all warnings, and with -g to get debug information; the optimize flag -O is optional -it could be -O2 to optimize more- and might improve performance of the generated plugin)

If you want to use C++ with dlopen & dlsym be sure to read the C++ dlopen mini-howto.

Don't forget to read documentation about Invoking GCC

If you want to avoid name mangling in genuine C++ code, declare your functions as extern "C".

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • It does "work" with `g++` which has a different role: to compile C++ code, not C code. It just happens that your C code is also valid C++ code. If you have used `new` instead of `testFunction` as the name, your source code won't be valid C++ (but remains valid in C) because `new` is a C++ keyword. – Basile Starynkevitch Aug 01 '16 at 16:31
2

You need to research "C++ name mangling".

Argument types and more are encoded in the final name the compiler generates.

If you don't want this (for example if you want the function to be callable from a C context), then you should make it extern "C".

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70