The question is very similar to this one, however none of the solutions mentioned there was helpful.
Suppose I have a shared library B with a function that uses a local global variable. This function is called from a second shared library C.
Both B and C are used by A, and I would expect each to have its own instance of the global variable, but somehow the compiler manages to link them to point to the same object (unlike Windows).
Can someone suggest a method to allow me having to different instances of the global variable in A?
Below is my code. When running a.out, I'd expect to get
1
calling from someCFunc(): 1
However, I get:
1
calling from someCFunc(): 2
b.h:
#ifndef _B_H_
#define _B_H_
extern "C" __attribute__ ((visibility("default"))) void myFunc();
#endif
b.cpp:
#include "b.h"
#include <iostream>
int myGlobal = 0;
extern "C" __attribute__ ((visibility("default"))) void myFunc()
{
++myGlobal;
std::cout << myGlobal << "\r\n";
}
c.h:
#ifndef _C_H_
#define _C_H_
extern "C" __attribute__ ((visibility("default"))) void someCFunc();
#endif
c.cpp
#include "c.h"
#include "b.h"
#include <iostream>
extern "C" __attribute__ ((visibility("default"))) void someCFunc()
{
std::cout << "calling from someCFunc(): ";
myFunc();
}
a.cpp:
#include "b.h"
#include "c.h"
int main(void)
{
myFunc();
someCFunc();
return 0;
}
buildscript:
rm *.so
rm *.out
g++ -fPIC -fvisibility=hidden -shared b.cpp -o libb.so
g++ -fPIC -fvisibility=hidden -shared b.cpp -o libb2.so
g++ -fPIC -fvisibility=hidden -shared c.cpp -o libc.so -l:libb.so
g++ a.cpp -fPIC -fvisibility=hidden -l:libb2.so -l:libc.so