Skip to content

Instantly share code, notes, and snippets.

@samskalicky
Last active January 25, 2020 07:09
Show Gist options
  • Save samskalicky/f153e082f59e1e9b08a037dd592a63c4 to your computer and use it in GitHub Desktop.
Save samskalicky/f153e082f59e1e9b08a037dd592a63c4 to your computer and use it in GitHub Desktop.
static singletons in shared libraries
class Registry {
public:
//change to:
//static Registry* get() __attribute__ ((visibility ("hidden") )) {
static Registry* get() {
static Registry inst;
std::cout << "Registry in: " << &inst << std::endl;
return &inst;
}
int size() {
return val;
}
void inc() {
val += 12;
}
private:
Registry() {val=42;}
int val;
};
#include <iostream>
#include "inc.h"
extern "C" {
int foo() {
std::cout << "in foo found myVar: " << Registry::get()->size() << std::endl;
Registry::get()->inc();
return 42;
}
}
all:
g++ -o main test.cpp -ldl -std=c++11
g++ -o libmylib.so -shared -fPIC -std=c++11 lib.cpp
cp libmylib.so libmylib2.so
clean:
rm -rf *.so main *~
########## with __attribute__ ###################
hello
foo is at: 0x7efd6600aba0
Registry in: 0x7efd6620c07c <-----------
in foo found myVar: 42
Registry in: 0x7efd6620c07c <-----------
foo is at: 0x7efd65e07ba0
Registry in: 0x7efd6600907c
in foo found myVar: 42
Registry in: 0x7efd6600907c
############ without __attribute__ ##################
hello
foo is at: 0x7f4391bccca0
Registry in: 0x7f4391dce084
in foo found myVar: 42
Registry in: 0x7f4391dce084
foo is at: 0x7f43919c9ca0
Registry in: 0x7f4391dce084
in foo found myVar: 54
Registry in: 0x7f4391dce084
#include <iostream>
#include <dlfcn.h>
void lookup(const char* path) {
void* handle = dlopen(path, RTLD_LAZY);
if (!handle) {
std::cout << "Error loading library: '" << path << "'\n" << dlerror() << std::endl;
}
const char* name = "foo";
void* func = dlsym(handle, name);
if (!func) {
std::cout << "Error getting function '" << name << "' from library\n" << dlerror() << std::endl;
}
void (*foo)() = (void(*)())func;
std::cout << "foo is at: " << func << std::endl;
foo();
}
int main() {
std::cout << "hello" << std::endl;
const char* path = "libmylib.so";
lookup(path);
const char* path2 = "libmylib2.so";
lookup(path2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment