Skip to main content
gamedev.net
🔒 Locked

Static char .... ???

Started by Xces 4 replies 400+ views
Original Post
Xces
Xces
Hello, i have a static variable in file "one.h" like this: static char settings[32]; When i try to fill the variable from file "two.cpp" which has an include to one.h, everything goes well. If i print the contents of the variable then i see that it is filled. But; When i call a function from "two.cpp" in "one.cpp" which uses that variable, it is empty again... How is this possible?
Sandman
Sandman
This is a global variable right?

The problem is you are trying to use a static global in two different files. This doesn''t work, all you are doing is creating two separate globals with exactly the same name in each file.

If you need to access a global variable in multiple files, you will need to declare it extern in the header, not static, and declare it ONCE in one of the .cpps without the extern keyword, and it will be OK.
Advanced Bug
Advanced Bug
What you have done is defining (instead of declaring) a variable in a .h file. As a result the variable gets defined in every .cpp that includes the .h file. Normally you would get linker errors, but since you have defined that variable static (which means that variable cannot be accessed from another source file) linker doesn''t complain, and you get many (two in your case) different variables with the same name.

Probably what you need is declaration:

extern char settings[32];

in "one.h" file, and definition:

char settings[32];

in one of the .cpp files.
Xces
Xces
Not quite...

I needed to declare it like this:
static char somestring[32];
in one.h,

and like this:
extern char somestring[32];
in two.h.

Thanx anyway
Sandman
Sandman
quote:
Original post by Xces
Not quite...

I needed to declare it like this:
static char somestring[32];
in one.h,

and like this:
extern char somestring[32];
in two.h.

Thanx anyway


Err, what compiler are you using? Because I am pretty sure that shouldn''t work.

The static keyword defines a global as being local to that file, ie not linked to any other files.
SabreMan
SabreMan
quote:
Original post by Xces
I needed to declare it like this:
static char somestring[32];
in one.h,

That means somestring has internal linkage.
quote:

and like this:
extern char somestring[32];
in two.h.

That means somestring has external linkage.

Since you are sharing somestring across translation units, you do not want internal linkage. Don''t use "static".


[ C++ FAQ Lite | ACCU | Boost | Python | Agile Manifesto! ]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.