Jump to content
  • Advertisement
Sign in to follow this  
Giallanon

Static variable in library, c++

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

If you intended to correct an error in the post then please contact us.

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

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!