1

I would like to have a struct that functions like this:

struct

  • member 1 (every instance of the struct has its own value of this)

  • static member (every struct shares this member)

I am aware that the static keyword does not do this. My question is, how can I mimic this behavior?

Could I create a member that is pointer to a global variable?

Is there some other better way to do this?

3
  • 4
    If the member is common to all structs why include it as a member? Commented Nov 5, 2015 at 20:41
  • I'm not sure you can, it is not object oriented. You cannot do struct::static_member in C. Commented Nov 5, 2015 at 20:42
  • Check this thread: stackoverflow.com/questions/6013373/… Commented Nov 5, 2015 at 20:43

1 Answer 1

3

Unlike structs in C++ which can have static data members, C structs don't have such a construct.

Since this is a common value for anyone that may use it, just declare it as a global:

int my_struct_common_val = 42;

struct my_struct {
    ...
};
Sign up to request clarification or add additional context in comments.

1 Comment

If this is in a header file then you will need to use extern int my_struct_common_val; with definition in exactly one .c file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.