Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable gets different values when used in different static methods

I have the following class that implements static methods that must use a single global array. It is defined as such:

//Defined in LockTrack.h file

enum LOCK_ID{
    LOCKID_0,
    LOCKID_1,
    LOCKID_2,

    LOCKID_COUNT
};

static LOCK_ID __glob_lock_ids[LOCKID_COUNT];


class CLockTrack
{
public:
    static void getLockedLocks(/*parameters*/)
    {
        //__glob_lock_ids = points to 0x015ef558 address in memory
        LOCK_ID lockID = __glob_lock_ids[0];
    }

    static void inline setLock(LOCK_ID lockID)
    {
        //__glob_lock_ids = points to 0x015ef330 address in memory
        __glob_lock_ids[lockID] = LOCK_ON_FLAG;
    }
};

But what happens is that the '__glob_lock_ids' pointer points to different memory locations in each method. Why? And how to fix this?

like image 568
c00000fd Avatar asked Jan 22 '26 11:01

c00000fd


1 Answers

Nope, that's not a global. Change it to

extern LOCK_ID __glob_lock_ids[LOCKID_COUNT];

and move

LOCK_ID __glob_lock_ids[LOCKID_COUNT];

into a single implementation file. Your version, static, will effectively create a new variable for each translation unit that includes the header.

like image 83
Luchian Grigore Avatar answered Jan 25 '26 02:01

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!