Reputation: 1477
I want to design a struct in C, which is like:
typedef struct {
const int HEADER;
int data;
} A_STRUCT;
I hope all the instances of this struct have the same known const HEADER value, e.g. 0x33
. Basically, I need a member variable which is initialized automatically in each instance of the struct. What is the correct way to do it in C (not C++)? Esp. how to initialize it?
Upvotes: 1
Views: 2500
Reputation:
Note: This answer is invalidated by an edit to the question, removing the objective of a "static member" like in C++. Leaving it here just for reference.
A static member in C++ is essentially a global variable that's scoped in the namespace of the struct
/class
. So something like this in C++:
foo.h:
struct foo
{
static int bar;
int baz;
};
foo.cpp:
int foo::bar = 0x33;
translates roughly to the following in C:
foo.h:
struct foo
{
int baz;
}
extern int foo_bar;
foo.c:
int foo_bar = 0x33;
Also note the keyword static
has an entirely different meaning in C, it declares the variable with static storage; it becomes inaccessible from other translation units.
Upvotes: 1