Mark S
Mark S

Reputation: 235

Single copy of global variables in Linux shared library

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

Upvotes: 2

Views: 3275

Answers (1)

syam
syam

Reputation: 15069

Both B and C are used by A, and I would expect each to have its own instance of the global variable

Your expectations are wrong. What you are observing here is the correct and expected behaviour. If what you expect was true, every single library out there would face a problem quite similar to the infamous diamond class hierarchy.

Can someone suggest a method to allow me having to different instances of the global variable in A?

As far as I know, this is not possible in C++. If you want to use different variables, you have to define them separately and pass a reference to your function:

// B
void myFunc(int& myVar) {
    ++myVar;
    std::cout << myVar << "\r\n";
}

// C
int myGlobalC = 0;
void someCFunc() {
    myFunc(myGlobalC);
}

// A
int myGlobalA = 0;
int main() {
    myFunc(myGlobalA);
    someCFunc();
}

Upvotes: 1

Related Questions