|
-
January 16th, 2009, 08:54 AM
#14
Re: initialize static variable in cpp file
 Originally Posted by MacDaddy C++
There can be only one!
Do you know the HighLander?? 
On a more serious note, that is the whole crux of the matter. The "line of code" which defines the static and initializes it (implicitly or explicitly) must be seen by the compiler only once for all of the translation usings that will be linked into the final program.
Typically this is best done by putting the code in a specific .cpp file. And thos post does NOT contract that, nor recommend the following approach (although it is useful in certain very specific cases...
This approach should make immediate sense to anyone who has used preprocessor directives to conditionally "dllExport" / "dllImport"...
SomeFile.h
Code:
class Foo
{
static SomeClass StaticInstance;
};
#ifdef SOME_FILE_CPP_COMPILING
Foo::StaticInstance(params);
#endof
SomeFile.cpp
Code:
#define SOME_FILE_CPP_COMPILING
#include "SomeFile.h"
This can also be accompished using the __FILE__ predefined value.
AGAIN, This is NOT recommended as a general practice. But for cases where the value of the static needs to be "published" (known to users of the header file), it provides a means that is guaranteed to remain "in sync" (A comment in the header file could easily differ from a value in an implementation file.
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|