0

I have a C++ DLL with 3 classes in it. I added a static boolean variable to my "stdafx" header file (since all of my classes include it) and am trying to use it. While all of my classes see my variable, they each seem to have a different instance of it. If I set the variable to true in once class then I'll notice that it's false in another class. Is there any way that I can create a variable that can be used across all classes only within the DLL?

2
  • Isn't stdafx your MSVS precompiled headers support? Should you perhaps not be modifying it? Commented Jan 5, 2012 at 18:55
  • I'm open to any ideas to help solve this issue. This made the most sense to me so I went with it.
    – Seb
    Commented Jan 5, 2012 at 18:57

2 Answers 2

4

Well, you labelled it static, so that's what happens. Instead, label it extern in headers and define it in one TU.

And don't modify stdafx; it's not yours. Use your own shared headers.

5
  • 4
    You are allowed to modify stdafx.h. The auto-generated comment in the file says so //stdafx.h : include file for standard system include files, or project specific include files that are used frequently, but are changed infrequently
    – Praetorian
    Commented Jan 5, 2012 at 19:00
  • @Praetorian: But it seems like a really bad idea. Mostly because it's auto-generated by the IDE; your bool will get lost at some point. Commented Jan 5, 2012 at 19:01
  • It is auto-generated, but only once when you create the project, and not modified by the IDE after that. I don't think it is possible to create your own precompiled header that can be used in conjunction with stdafx.h so it might just be the only option.
    – Praetorian
    Commented Jan 5, 2012 at 19:04
  • 2
    It does not get regenerated, ever. So no risk of losing anything you put there. On the other hand, I would not put any code or interfaces in it, only headers for precompilation.
    – crashmstr
    Commented Jan 5, 2012 at 19:04
  • I'll create a shared header file used by all classes. Thank you
    – Seb
    Commented Jan 5, 2012 at 19:13
2

Your variable is static and you're declaring it in stdafx.h which is included by all source files in your project. This means each translation unit will contain its own copy of the variable, which is exactly the behavior you're seeing.

To solve this problem, declare the variable in stdafx.cpp

bool MyBool = false;

Then extern it in stdafx.h

extern bool MyBool;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.