# Static variable in library, c++

This topic is 4011 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

It's not the first time I face this problem, but still I haven't figured a good solution, that's why I'm asking for an advice. I'm working on a library for a little game; inside the library I've implemented a factory pattern that allow me to "spawn" weapons. Inside the library I've a set of weapon classes (derived from BaseWeapon). Every weapon class has it's own factory (derived from BaseWeaponFactory); every derived factory has a static variable that is used to auto-register the factory...I think this is the standard way of doing factory, anyway here's a little code to let you understand better what I'm doing
class BaseWeapon
{
...
}

class WeaponFactory
{
public:
WeaponFactory (const char *strWeaponName);
virtual ~WeaponFactory();

static Weapon*  Spawn (const char *strWeaponName) = 0;

protected:
virtual Weapon* CreateNew () = 0;

private:
....
}


class Rifle : public BaseWeapon
{
...
}

class RifleFactory : public WeaponFactory
{
public:
RifleFactory () : WeaponFactory("Rifle") {}
~RifleFactory() {};

protected:
Weapon*  CreateNew ()   {return new Rifle;}

private:
static RifleFactory autoRegistedMe;
}


Note: If I use this code inside a standard exe (not inside a library) it works. Problem arise only if I put this code inside a lib. The "static RifleFactory autoRegistedMe" is used to autoregister the factory but this is not working inside the lib because I guess the compiler is optimizing the code throwing away the variable as it's not used anywhere in the code. The only way I've found to let this work, is to use a separate header where I list all the static var and then to include this header somewhere in the exe code, something like this:
#include "Rifle.h"
RifleFactory RifleFactory::autoRegistedMe;


Then, somewhere in the exe code, I've to #include this file. I don't like this approach beacause every time I add a new weapoan, I've to add the static to this big header file and also, I've to remember every time I use the library to include this header somewhere in the code. Is there any workaround for this ? I'm using MSVC++ 2003

1. 1
2. 2
3. 3
Rutin
22
4. 4
frob
18
5. 5

• 33
• 13
• 10
• 10
• 12
• ### Forum Statistics

• Total Topics
632569
• Total Posts
3007121

×