How to export specific symbol from executables in GNU/Linux - c++

While loading dynamic libraries by ::dlopen(), exporting symbols from executables can be done by -rdynamic option, but it exports all the symbols of the executable, which results in bigger binary size.
Is there a way to export just specific function(s)?
For example, I have testlib.cpp and main.cpp as below:
testlib.cpp
extern void func_export(int i);
extern "C" void func_test(void)
{
func_export(4);
}
main.cpp
#include <cstdio>
#include <dlfcn.h>
void func_export(int i)
{
::fprintf(stderr, "%s: %d\n", __func__, i);
}
void func_not_export(int i)
{
::fprintf(stderr, "%s: %d\n", __func__, i);
}
typedef void (*void_func)(void);
int main(void)
{
void* handle = NULL;
void_func func = NULL;
handle = ::dlopen("./libtestlib.so", RTLD_NOW | RTLD_GLOBAL);
if (handle == NULL) {
fprintf(stderr, "Unable to open lib: %s\n", ::dlerror());
return 1;
}
func = reinterpret_cast<void_func>(::dlsym(handle, "func_test"));
if (func == NULL) {
fprintf(stderr, "Unable to get symbol\n");
return 1;
}
func();
return 0;
}
Compile:
g++ -fPIC -shared -o libtestlib.so testlib.cpp
g++ -c -o main.o main.cpp
I want func_export to be used by the dynamic library, but hide the func_not_export.
If link with -rdynamic,
g++ -o main -ldl -rdynamic main.o
, both functions are exported.
If not link with -rdynamic,
g++ -o main_no_rdynamic -ldl main.o
, I got runtime error Unable to open lib: ./libtestlib.so: undefined symbol: _Z11func_exporti
Is it possible to achieve the requirement that only export the specific function?

Is there a way to export just specific function(s)?
We needed this functionality, and added --export-dynamic-symbol option to the Gold linker here.
If you are using Gold, build a recent version and you'll be all set.
If you are not using Gold, perhaps you should -- it's much faster, and has the functionality you need.

Related

(solved) C++ Load one Shared Object with dependencies and access their functions

OS Linux Ubuntu 18.04, gcc 7.4.0
A program should load one SO which is dependent on other SOs. All exported functions of all SOs should be called by the program.
I found serveral related questions but none dealing explicitly with this situation.
Here is an exmple what I am trying to do:
There are 3 shared libraries and one application:
libtest1.so has a extern "C" print function
libtest2.so has a base class "Base" with a function usig the C-function
libtest3.so has a derived class "Test" with a function using the C-function-
DllTest Application: loads the *.so's
This is what the application should to
pHandle = OpenSharedLib("./libtest1.so"); # works
OpenSymbol(pHandle, "GetName"); # works
CloseLib(pHandle);
pHandle = OpenSharedLib("./libtest2.so"); # error
OpenSymbol(pHandle, "GetName");
OpenSymbol(pHandle, "printBase");
CloseLib(pHandle);
pHandle = OpenSharedLib("./libtest3.so");
OpenSymbol(pHandle, "GetName");
OpenSymbol(pHandle, "printBase");
OpenSymbol(pHandle, "print");
CloseLib(pHandle);
The error was that dlopen() failed to load due to an undefined symbol: ./libtest2.so: undefined symbol: GetName". The nm output shows that the symbol is missing, but I did not find out how I could prevent that.
The basic idea is to have a 'front SO' that is collecting all kind of seprate SO's and present a unified library to the program. In the example the program should only load libtest3.so. It should then be able to load any symbol as long as it was exposed by any of the single SOs.
My Question: Is it possible to do what I want and how? Or in other words: what is my error?
Here is the code and the commands I used to compile them is given below.
lib1.h, lib1.cpp for libtest1.so
lib2.h, lib2.cpp for libtest2.so
lib3.cpp for libtest3.so
DllTest.cpp the application
libtest1.so
header
extern "C" __attribute__((visibility("default"))) const char* GetName();
Cpp
#include <stdio.h>
#include <stdlib.h>
#include "lib1.h"
__attribute__((visibility("default"))) const char* GetName()
{
return "Hello from lib1";
}
compiled with
g++ -c -fvisibility=hidden -fPIC -o lib1.o lib1.cpp
g++ -shared -o libtest1.so lib1.o
libtest2.so
Header
#include <stdio.h>
#include <stdlib.h>
class __attribute__((visibility("default"))) Base
{
public:
Base();
virtual ~Base();
const char* printBase();
int nTest;
};
Cpp
#include <stdio.h>
#include <stdlib.h>
#include "lib2.h"
#include "lib1.h" // for GetName()
Base::Base()
{ nTest=1; }
Base::~Base()
{ }
const char* Base::printBase()
{ return GetName(); }
compiled with
g++ -c -fvisibility=hidden -fPIC -o lib2.o lib2.cpp
g++ -shared -o libtest2.so -L. -ltest1 lib2.o
libtest3.so
#include <stdio.h>
#include <stdlib.h>
#include "lib1.h"
#include "lib2.h"
class __attribute__((visibility("default"))) Test : public Base
{
public:
Test();
virtual ~Test();
const char* print();
};
Test::Test()
{ }
Test::~Test()
{ }
const char* Test::print() {
char* pChar = (char*)GetName();
printf( "hello from lib3: %d", nTest);
return "test3";
}
Compiled
g++ -c -fvisibility=hidden -fPIC -o lib3.o lib3.cpp
g++ -shared -o libtest3.so -L. -ltest1 -ltest2 lib3.o
** Loading Application **
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <dlfcn.h>
void OpenSymbol(void* pHandle, char* strName)
{
typedef char* (*pfnChar)(void);
pfnChar pFunction = NULL;
char* cError;
printf(" Find symbol %s\n", strName);
dlerror();
pFunction = (pfnChar)dlsym( pHandle, strName );
cError = dlerror();
if (cError != 0) {
std::cout << cError << std::endl;
exit(1); }
printf(" Exec symbol: %p\n", pFunction );
std::cout << pFunction() << std::endl;
}
void* OpenSharedLib(char* strName)
{
void* pHandle;
char* cError;
printf(" open lib %s\n", strName);
dlerror();
pHandle = dlopen( strName, RTLD_NOW );
cError = dlerror();
if (cError != 0) {
std::cout << cError << std::endl;
exit(1); }
printf(" found DLL %p\n", pHandle );
return pHandle;
}
void* CloseLib(void* pHandle)
{ dlclose(pHandle); }
main()
{
void* pHandle;
pHandle = OpenSharedLib("./libtest1.so");
OpenSymbol(pHandle, "GetName");
CloseLib(pHandle);
pHandle = OpenSharedLib("./libtest2.so");
OpenSymbol(pHandle, "GetName");
OpenSymbol(pHandle, "printBase");
CloseLib(pHandle);
pHandle = OpenSharedLib("./libtest3.so");
OpenSymbol(pHandle, "GetName");
OpenSymbol(pHandle, "printBase");
OpenSymbol(pHandle, "print");
CloseLib(pHandle);
std::cout << "done" << std::endl;
}
Running nm -DC shows that for the last two libraries some symbold are not exported.
symbols libtest1.so:
...
000000000000057a T GetName
symbols libtest2.so:
...
U GetName
U operator delete(void*, unsigned long)
000000000000094c T Base::printBase()
00000000000008da T Base::Base()
00000000000008da T Base::Base()
0000000000000920 T Base::~Base()
0000000000000902 T Base::~Base()
0000000000000902 T Base::~Base()
0000000000200e08 V typeinfo for Base
0000000000000969 V typeinfo name for Base
0000000000200de8 V vtable for Base
U vtable for __cxxabiv1::__class_type_info
symbols libtest3.so:
...
U GetName
U printf
U operator delete(void*, unsigned long)
U Base::Base()
U Base::~Base()
0000000000000ab2 T Test::print()
0000000000000a2a T Test::Test()
0000000000000a2a T Test::Test()
0000000000000a86 T Test::~Test()
0000000000000a58 T Test::~Test()
0000000000000a58 T Test::~Test()
U typeinfo for Base
0000000000200df0 V typeinfo for Test
0000000000000b0f V typeinfo name for Test
0000000000200dd0 V vtable for Test
U vtable for __cxxabiv1::__si_class_type_info
Finaly, the output DllTest
open lib ./libtest1.so
found DLL 0x55965d711ea0
Find symbol GetName
Exec symbol: 0x7f902c38157a
Hello from lib1
open lib ./libtest2.so
./libtest2.so: undefined symbol: GetName
Edit after selected answer
There are two main issues that code is not working. First, loading fails because the dynamic loader does not find the dependent shared objects, i.e. when loading libtest2.so it fails to locate libtest1.so and when loading libtest3.so it fails to locate libtest2.so and libtest1.so. That can be fixed by adding the path during linking. Second, accessing non extern "C" objects like classes require an object that must be created in the shared object. Therefore lib2.h/cpp, lib2.h/cpp and DllTest.cpp must be refactored.
For convenience here is the full compilation sequence with the corrections from the answer
g++ -c -fvisibility=hidden -fPIC -o lib1.o lib1.cpp
g++ -shared -o libtest1.so lib1.o
g++ -c -fvisibility=hidden -fPIC -o lib2.o lib2.cpp
g++ -shared -o libtest2.so -Wl,-rpath,$PWD -L.lib2.o -ltest1
g++ -c -fvisibility=hidden -fPIC -o lib3.o lib3.cpp
g++ -shared -o libtest3.so -Wl,-rpath,$PWD -L. lib3.o -ltest1 -ltest2
g++ -o DllTest DllTest.cpp -ldl
With this the code allows the use of the const char* GetName() function no matter which shared object of the three is loaded.
As a start, change the order of the arguments in the link-commands
g++ -g -shared -o libtest2.so -L. lib2.o -ltest1
g++ -g -shared -o libtest3.so -L. lib3.o -ltest1 -ltest2
Note: it's not necessary with every linker, but the newer gold linker only resolves "from-left-to-right". Also there's a -Wl,--no-undefined option, which is very useful to catch these error.
Then add rpath into these commands so that the shared objects find their dependencies run-time:
g++ -g -shared -o libtest2.so "-Wl,-rpath,${PWD}" -L. lib2.o -ltest1
g++ -g -shared -o libtest3.so "-Wl,-rpath,${PWD}" -L. lib3.o -ltest1 -ltest2
After linkage, readelf -d should show the RPATH like this:
$ readelf -d libtest3.so |head -n10
Dynamic section at offset 0xdd8 contains 28 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libtest1.so]
0x0000000000000001 (NEEDED) Shared library: [libtest2.so]
0x0000000000000001 (NEEDED) Shared library: [libstdc++.so.6]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x000000000000001d (RUNPATH) Library runpath: [/home/projects/proba/CatMan]
(Also there is libtool to deal with shared libraries.)
Mind you, because of name-mangling, the following change should be performed (though it is compiler-specific)
- OpenSymbol(pHandle, "printBase");
+ OpenSymbol(pHandle, "_ZN4Base9printBaseEv");

How to compile a cpp and then link it to a shared library

I want to have the functions which are defined in another .cpp file become available in another simulation tool.
I found the following code in this question: -finstrument-functions doesn't work with dynamically loaded g++ shared objects (.so)
Trace.cpp
#include <stdio.h>
#ifdef __cplusplus
extern "C"
{
void __cyg_profile_func_enter(void *this_fn, void *call_site)
__attribute__((no_instrument_function));
void __cyg_profile_func_exit(void *this_fn, void *call_site)
__attribute__((no_instrument_function));
}
#endif
void __cyg_profile_func_enter(void* this_fn, void* call_site)
{
printf("entering %p\n", (int*)this_fn);
}
void __cyg_profile_func_exit(void* this_fn, void* call_site)
{
printf("exiting %p\n", (int*)this_fn);
}
Trace.cpp is compiled by doing:
g++ -g -finstrument-functions -Wall -Wl,-soname,libMyLib.so.0 -shared -fPIC -rdynamic MyLib.cpp MyLibStub.cpp Trace.cpp -o libMyLib.so.0.0
ln -s libMyLib.so.0.0 libMyLib.so.0
ln -s libMyLib.so.0.0 libMyLib.so
g++ MainStatic.cpp -g -Wall -lMyLib -L./ -o MainStatic
g++ MainDynamic.cpp -g -Wall -ldl -o MainDynamic
Note that I don't need: MyLib.cpp and MyLibStub.cpp.
Instead compiled Trace.cpp doing:
g++ -g -finstrument-functions -Wall -Wl,-soname,libMyLib.so.0 -shared -fPIC -rdynamic Trace.cpp -o libMyLib.so.0.0
What I've tried:
The shared object where I want to have Trace.cpp is obtained by:
opp_makemake -f --deep --no-deep-includes --make-so -I . -o veins -O out -I../../inet/src/util/headerserializers/sctp/headers -L../../inet/src -linet
I added -L and -l:
opp_makemake -f --deep --no-deep-includes --make-so -I . -o veins -L /home/user/Desktop/test/ -lMyLib -O out -I../../inet/src/util/headerserializers/sctp/headers -L../../inet/src -linet
and got:
/usr/bin/ld: cannot find -lMyLib
I also tried:
opp_makemake -f --deep --no-deep-includes --make-so -I . -o veins /home/user/Desktop/test/libMyLib.so.0.0 -O out -I../../inet/src/util/headerserializers/sctp/headers -L../../inet/src -linet
which compiled successfully but the application crashed:
Error during startup: Cannot load library
'../../src//libveins.so': libMyLib.so.0: cannot open shared object
file: No such file or directory.
Question:
How to compile Trace.cpp correctly?
How to link it with the rest of the shared library?
As you might notice I am not very experienced with compiling, linking and similar. So, any extra explanation is very welcome!
As #Flexo restates what #EmployedRussian said in the linked question, the main point is to get your implementation of __cyg_profile_func_*** before the one provided by libc.so.6.
One method to do this, is to use the LD_PRELOAD environment variable. Here you can read what LD_PRELOAD does and how it works.
To use the LD_PRELOAD trick you will need to compile your implementation of the above-mentioned functions as a shared library.
You can do this by doing:
g++ -shared -fPIC myImp.cc -o myImp.so -ldl
Once you get the .so file, navigate to the directory where your executable is located and do:
LD_PRELOAD=<path/to/myImp.so>- ./<myExecutable>
For shared libraries, dynamic linking is used. Meaning:
resolving of some undefined symbols (is postponed) until a program is run.
By using LD_PRELOAD you resolve the symbols of your interest before letting the linked do that.
Here you have an implementation of myImp.cc, which I took from: https://groups.google.com/forum/#!topic/gnu.gcc.help/a-hvguqe10I
The current version lacks proper implementation for __cyg_profile_func_exit, and I have not been able to demangle the function names.
#ifdef __cplusplus
extern "C"
{
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dlfcn.h>
void __cyg_profile_func_enter(void *this_fn, void *call_site)__attribute__((no_instrument_function));
void __cyg_profile_func_exit(void *this_fn, void *call_site)__attribute__((no_instrument_function));
}
#endif
static FILE *fp;
int call_level=0;
void * last_fn;
void __cyg_profile_func_enter(void *this_fn, void *call_site)
{
Dl_info di;
if (fp == NULL) fp = fopen( "trace.txt", "w" );
if (fp == NULL) exit(-1);
if ( this_fn!=last_fn) ++call_level;
for (int i=0;i<=call_level;i++)
{
fprintf(fp,"\t");
}
//fprintf(fp, "entering %p\n", (int *)this_fn);
fprintf(fp, "entering %p", (int *)this_fn);
if (dladdr(this_fn, &di)) {
fprintf(fp, " %s (%s)", di.dli_sname ? di.dli_sname : "<unknown>", di.dli_fname);
}
fputs("\n", fp);
(void)call_site;
last_fn = this_fn;
}
void __cyg_profile_func_exit(void *this_fn, void *call_site)
{
--call_level;
for (int i=0;i<=call_level;i++) fprintf(fp,"\t");
fprintf(fp, "exiting %p\n", (int *)this_fn);
(void)call_site;
}
Another option for function tracing which uses LD_PRELOAD is used by LTTng, in the section Function Tracing, but I have never used it...

How to mix C++ and C correctly

I am having some problems with this: I need to write a C wrapper for a C++ library. Say I have 3 files:
wrapper.h
typedef struct Foo Foo;
Foo* create_foo();
wrapper.cpp
extern "C" {
#include "wrapper.h"
}
#include "foo.h"
Foo* create_foo() {
return new Foo;
}
foo.h
class Foo {
public:
Foo();
};
This compiles fine:
clang++ -std=c++14 wrapper.cpp foo.h wrapper.h -shared -fPIC
clang++ -shared -o libbindings.so a.out
but when compiling the program that uses the C wrapper (it is compiler and linked by the programming language that uses the wrapper - Crystal), I get an undefined reference to create_foo() and a linker error collect2: error: ld returned 1 exit status. How can I debug this (and what am I doing wrong)?
Here is a working example:
wrapper.h (C & C++ aware)
#ifndef WRAPPER_H_
#define WRAPPER_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct CPPClass CPPClass;
CPPClass* CPPClass_new();
void CPPClass_do_something(CPPClass* cppclass);
int CPPClass_get_state(CPPClass* cppclass);
void CPPClass_delete(CPPClass* cppclass);
#ifdef __cplusplus
}
#endif
#endif /* WRAPPER_H_ */
wrapper.cpp (C++ only)
#include "wrapper.h"
class CPPClass
{
int state;
public:
CPPClass(): state(0) {}
void do_something() { ++state; }
int get_state() const { return state; }
};
extern "C" CPPClass* CPPClass_new()
{
return new CPPClass;
}
extern "C" void CPPClass_do_something(CPPClass* cppclass)
{
cppclass->do_something();
}
extern "C" int CPPClass_get_state(CPPClass* cppclass)
{
return cppclass->get_state();
}
extern "C" void CPPClass_delete(CPPClass* cppclass)
{
delete cppclass;
}
use-wrapper.c (C only)
#include <stdio.h>
#include "wrapper.h"
int main(void)
{
CPPClass* cppclass = CPPClass_new();
if(!cppclass)
{
printf("ERROR: failed to create CPPClass:\n");
return 1;
}
printf("state: %d\n", CPPClass_get_state(cppclass));
CPPClass_do_something(cppclass);
printf("state: %d\n", CPPClass_get_state(cppclass));
CPPClass_delete(cppclass);
}
Compile CPP
g++ -std=c++11 -shared -fPIC -o libwrapper.so wrapper.cpp
Compile C
gcc -o use-wrapper use-wrapper.c -L. -lwrapper -lstdc++
Output:
$ ./use-wrapper
state: 0
state: 1
Hope that helps.
You are creating a shared object named a.out, then another shared object named libbindings.so that ostensibly links to a.out but references nothing from it. Now if a set of input files doesn't have any undefined symbols, no libraries are searched or added to the output. So libbindings.so is essentially an empty library. Verify:
% nm a.out | grep create_foo
00000000000006bc T create_foo
% nm libbindings.so | grep create_foo
%
If you have several source files, you should build an object file from each source (use -c compilation flag), (then optionally combine the objects into a static library --- skip this step if you are not releasing static libraries) then build a shared object from previously built objects:
clang++ -c -fPIC foo.cpp
clang++ -c -fPIC bar.cpp
clang++ -shared -o libfoobar.so foo.o bar.o
If you only have one source, or very few source files you can easily compile together, you can build the shared library in one step:
clang++ -std=c++14 wrapper.cpp somethingelse.cpp -shared -fPIC -o libbindings.so
This is not recommended for large projects.

How to pass arguments to a method loaded from a static library in CPP

I'm trying to write a program to use a static library of a C++ code into another C++ code. The first C++ code is hello.cpp:
#include <iostream>
#include <string.h>
using namespace std;
extern "C" void say_hello(const char* name) {
cout << "Hello " << name << "!\n";
}
int main(){
return 0;
}
The I made a static library from this code, hello.a, using this command:
g++ -o hello.a -static -fPIC hello.cpp -ldl
Here's the second C++ code to use the library, say_hello.cpp:
#include <iostream>
#include <string>
#include <dlfcn.h>
using namespace std;
int main(){
void* handle = dlopen("./hello.a", RTLD_LAZY);
cout<<handle<<"\n";
if (!handle) {
cerr<<"Cannot open library: "<<dlerror()<<'\n';
return 1;
}
typedef void (*hello_t)();
dlerror(); // reset errors
hello_t say_hello = (hello_t) dlsym(handle, "say_hello");
const char *dlsym_error = dlerror();
if (dlsym_error) {
cerr<<"Cannot load symbol 'say_hello': "<<dlsym_error<<'\n';
dlclose(handle);
return 1;
}
say_hello("World");
dlclose(handle);
return 0;
}
Then I compiled say_hello.cpp using:
g++ -W -ldl say_hello.cpp -o say_hello
and ran ./say_hello in the command line. I expected to get Hello World! as output, but I got this instead:
0x8ea4020
Hello ▒▒▒▒!
What is the problem? Is there any trick to make compatibility for method's argument like what we use in ctypes or what?
If it helps I use a lenny.
EDIT 1:
I have changed the code and used a dynamic library, 'hello.so', which I've created using this command:
g++ -o hello.so -shared -fPIC hello.cpp -ldl
The 6th line of the code changed to:
void* handle = dlopen("./hello.so", RTLD_LAZY);
When I tried to compile say_hello.cpp, I got this error:
say_hello.cpp: In function ‘int main()’:
say_hello.cpp:21: error: too many arguments to function
I also tried to compile it using this line:
g++ -Wall -rdynamic say_hello.cpp -ldl -o say_hello
But same error raised. So I removed the argument "World" and the it has been compiled with no error; but when I run the executable, I get the same output like I have mentioned before.
EDIT 2:
Based on #Basile Starynkevitch 's suggestions, I changed my say_hello.cpp code to this:
#include <iostream>
#include <string>
#include <dlfcn.h>
using namespace std;
int main(){
void* handle = dlopen("./hello.so", RTLD_LAZY);
cout<<handle<<"\n";
if (!handle) {
cerr<<"Cannot open library: "<<dlerror()<<'\n';
return 1;
}
typedef void hello_sig(const char *);
void* hello_ad = dlsym(handle, "say_hello");
if (!hello_ad){
cerr<<"dlsym failed:"<<dlerror()<<endl;
return 1;
}
hello_sig* fun = reinterpret_cast<hello_sig*>(hello_ad);
fun("from main");
fun = NULL;
hello_ad = NULL;
dlclose(handle);
return 0;
}
Before that, I used below line to make a .so file:
g++ -Wall -fPIC -g -shared hello.cpp -o hello.so
Then I compiled say_hello.cpp wth this command:
g++ -Wall -rdynamic -g say_hello.cc -ldl -o say_hello
And then ran it using ./say_hello. Now everything is going right. Thanks to #Basile Starynkevitch for being patient about my problem.
Functions never have null addresses, so dlsym on a function name (or actually on any name defined in C++ or C) cannot be NULL without failing:
hello_t say_hello = (hello_t) dlsym(handle, "say_hello");
if (!say_hello) {
cerr<<"Cannot load symbol 'say_hello': "<<dlerror()<<endl;
exit(EXIT_FAILURE);
};
And dlopen(3) is documented to dynamically load only dynamic libraries (not static ones!). This implies shared objects (*.so) in ELF format. Read Drepper's paper How To Use Shared Libraries
I believe you might have found a bug in dlopen (see also its POSIX dlopen specification); it should fail for a static library hello.a; it is always used on position independent shared libraries (like hello.so).
You should dlopen only position independent code shared objects compiled with
g++ -Wall -O -shared -fPIC hello.cpp -o hello.so
or if you have several C++ source files:
g++ -Wall -O -fPIC src1.cc -c -o src1.pic.o
g++ -Wall -O -fPIC src2.cc -c -o src2.pic.o
g++ -shared src1.pic.o src2.pic.o -o yourdynlib.so
you could remove the -O optimization flag or add -g for debugging or replace it with -O2 if you want.
and this works extremely well: my MELT project (a domain specific language to extend GCC) is using this a lot (generating C++ code, forking a compilation like above on the fly, then dlopen-ing the resulting shared object). And my manydl.c example demonstrates that you can dlopen a big lot of (different) shared objects on Linux (typically millions, and hundred of thousands at least). Actually the limitation is the address space.
BTW, you should not dlopen something having a main function, since main is by definition defined in the main program calling (perhaps indirectly) dlopen.
Also, order of arguments to g++ matters a lot; you should compile the main program with
g++ -Wall -rdynamic say_hello.cpp -ldl -o say_hello
The -rdynamic flag is required to let the loaded plugin (hello.so) call functions from inside your say_hello program.
For debugging purposes always pass -Wall -g to g++ above.
BTW, you could in principle dlopen a shared object which don't have PIC (i.e. was not compiled with -fPIC); but it is much better to dlopen some PIC shared object.
Read also the Program Library HowTo and the C++ dlopen mini-howto (because of name mangling).
example
File helloshared.cc (my tiny plugin source code in C++) is
#include <iostream>
#include <string.h>
using namespace std;
extern "C" void say_hello(const char* name) {
cout << __FILE__ << ":" << __LINE__ << " hello "
<< name << "!" << endl;
}
and I am compiling it with:
g++ -Wall -fPIC -g -shared helloshared.cc -o hello.so
The main program is in file mainhello.cc :
#include <iostream>
#include <string>
#include <dlfcn.h>
#include <stdlib.h>
using namespace std;
int main() {
cout << __FILE__ << ":" << __LINE__ << " starting." << endl;
void* handle = dlopen("./hello.so", RTLD_LAZY);
if (!handle) {
cerr << "dlopen failed:" << dlerror() << endl;
exit(EXIT_FAILURE);
};
// signature of loaded function
typedef void hello_sig_t(const char*);
void* hello_ad = dlsym(handle,"say_hello");
if (!hello_ad) {
cerr << "dlsym failed:" << dlerror() << endl;
exit(EXIT_FAILURE);
}
hello_sig_t* fun = reinterpret_cast<hello_sig_t*>(hello_ad);
fun("from main");
fun = NULL; hello_ad = NULL;
dlclose(handle);
cout << __FILE__ << ":" << __LINE__ << " ended." << endl;
return 0;
}
which I compile with
g++ -Wall -rdynamic -g mainhello.cc -ldl -o mainhello
Then I am running ./mainhello with the expected output:
mainhello.cc:7 starting.
helloshared.cc:5 hello from main!
mainhello.cc:24 ended.
Please notice that the signature hello_sig_t in mainhello.cc should be compatible (homomorphic, i.e. the same as) with the function say_hello of the helloshared.cc plugin, otherwise it is undefined behavior (and you probably would have a SIGSEGV crash).

LD_PRELOAD help

I'm trying to use LD_PRELOAD.
original.cpp
void myPuts() {
puts ("Hello myPuts");
}
int main() {
myPuts();
return 0;
}
hacked.cpp
void myPuts() {
std::cout >> "Hello hacked myPuts";
}
I compile original.cpp:
g++ original.cpp
And hacked.cpp:
g++ -shared -fPIC hacked.cpp
I try:
LD_PRELOAD=./hacked.so ./original.out
The string "Hello hacked myPuts" should be seen, by "Hello myPuts" appears.
(If I try to "overwrite" the puts function, it works correctly)
What am I missing?
From man ld.so
LD_PRELOAD
A whitespace-separated list of additional, user-specified, ELF shared libraries to be loaded before all others. This can be used to selectively override functions in other shared libraries.
If myPuts was in shared library linked to main application it would work, but not when
myPuts exists in the application and does not resolved in an external library.
You should have:
main.cpp
int main() {
myPuts();
return 0;
}
original.cpp
void myPuts() {
puts ("Hello myPuts");
}
hacked.cpp
void myPuts() {
std::cout << "Hello hacked myPuts";
}
Compiling all:
g++ -shared -fPIC original.cpp -o liboriginal.so
g++ -shared -fPIC hacked.cpp -o libhacked.so
g++ main.cpp -loriginal -o main.out
And using:
LD_PRELOAD=./libhacked.so ./main.out