Sign in to follow this  

static variables (from "Thinking in C++)

This topic is 4529 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

Hello all According to this online book (Thinking in C++) static variables are variables that are limited to it's file scope and, when inside a function, retains it's value between function calls. I get the last bit, but it doesn't look like the first part is true anymore. If one links the following files, there should be a error msg, but it compiles just fine (C++ builder 5) FileStatic2.cpp extern int fs; void func() { fs = 100; } FileStatic.cpp #include "Filestatic2.cpp" #include <iostream> #include <conio.h> using namespace std; static int fs; int main() { fs = 1; func(); cout << fs << endl; getch(); } It looks like as long as the variable is outside any function it will be a global variable (and have external linkage?). So is the book wrong or just out of date? Thanks in advance.

Share this post


Link to post
Share on other sites
Since FileStatic.cpp #includes FileStatic2.cpp, they are really
one and the same "translation unit" to the compiler. So the
variable "fs" is accessible to func().

Try taking out the #include "FileStatic2.cpp", compile the two CPPs separately,
and then link them to create the executable. You'll get a linker error.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Well it defaults to it's file scope unless you do an

extern int fs;

like you did in FileStatic2.cpp. Then of course, it is in scope for both files. That is the correct behavior.

Share this post


Link to post
Share on other sites
Remember that what the preprocessor does is essentially just somewhat glorified copypasting. An #include directive is *physically* replaced by the full contents of the header being included (recursively preprocessing the header in the process). The compiler itself has *no* concept of "headers" - all it will see is a single file with all the headers pasted in - a "translation unit" in Standardese.

Share this post


Link to post
Share on other sites
since when can you extern a static variable? I could have sworn that was a no-no...

[edit]
that compiled for me, too. Strange. I guess I was wrong about that..

Share this post


Link to post
Share on other sites

This topic is 4529 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this