static char array behaving unexpectedly across classes
I know this will have a easy answer but am stumped. I've simplified the code as much as possible to get to the point.
I have a simple header file, call it a.h
which has the below and nothing more (it acts as a global settings file for all files in my project that choose to include it)
#ifndef A_H
#define A_H
namespace settings{
static char n开发者_如何学Came[16]={'\0'};
}
#endif
I then have another class, with its own header file, lets call it b.cpp (with b.h not shown)
#include "a.h"
void B::doSomething()
{
strcpy(settings::name,"I like Dogs");
}
Lastly, the third class which access' settings::name, call it c.cpp (with c.h not shown)
#include "a.h"
void C::printSomething()
{
printf("Some Girls Say %s\n",settings::name);
}
Alas, all that gets printed is "Some Girls Say ". What gives? I don't understand how settings::name isn't surviving function destruction of B::doSomething() (I can only guess this is the issue). Is strcpy being lazy and just pointing settings::name to where "I Like Dogs" begins rather than actually acting like strdup?
Any help and workaround is much appreciated. Thanks!
EDIT: For further clarity, B.doSomething() is invoked before C.printSomething().
the static
keyword links the name
into each translation unit it is included in, so each .cpp file basically has its own version of name
.
What you want to do is put the name
you want to share in one .cpp file (without the static
and declare it with extern
linkage in the .h file.
so that's:
a.cpp
namespace settings {
char name[16] = { 0 };
}
a.h
namespace settings {
extern char name[16];
}
b.cpp
void B::doSomething()
{
strcpy(settings::name,"I like Dogs");
}
c.cpp
#include "a.h"
void C::printSomething()
{
printf("Some Girls Say %s\n",settings::name);
}
By including that header in two source files, you have two separate storage locations. Including the header is a bit like just pasting that code into the source files. So they each have their own static variable called 'name'.
To get this to do what you want, you need to:
- Use extern, not static, in the header. This effectively means each file including the header will expect to reference a variable external to it.
- Define the variable in one of your source files. It needs to be defined somewhere, once. Don't use static or extern when defining it.
First of all write in a.cpp
namespace settings{
char name[16];
}
then ensure
B::doSomething()
is called.
精彩评论