开发者

Alternative to member variables in C

开发者 https://www.devze.com 2023-03-07 03:21 出处:网络
I have a file with several related functions which need to share a piece of data.While I would like to avoid the use of a global variable开发者_开发问答,The best solution I can think of is to declare

I have a file with several related functions which need to share a piece of data. While I would like to avoid the use of a global variable开发者_开发问答, The best solution I can think of is to declare a static in the file, but I'd like to restrict the scope to the file. I think that can be done with a static declaration. Are there other, superior alternatives?

In an object oriented environment, they would all be members of a class.


While a static would work, I think what you really want is a struct. Each function would take this struct as a param. So something like:

typedef struct mystruct_s {
    ...
} mystruct_t;

void myfunc1(mystruct_t *mystruct);
void myfunc2(mystruct_t *mystruct);

One advantage to this approach is that its thread-safe. ie, you could have multiple instances of mystruct running at the same time. Its also cleaner than having what's essentially a global variable (even if it is restricted in scope to one file).


Nope, declaring a global static variable pretty much covers what you need to do (provided that the variable needs to change; otherwise, use a macro). You can declare a static variable at the global level and have it be private to the file.

Also, be aware that this is totally not threadsafe.


A static will restrict the scope to the file, but there will only be one of then. That means you can only ever have one user of that set of functions if there's any state involved.

It's better to have a handle with a lifecycle that you can have scoped however you need it. To wit:

Foo * handle = foo_create();  // Allocates and initializes a structure

foo_operation1(handle);
foo_operation2(handle);

foo_destroy(handle);          // Deallocates the structure

This guarantees that only code that knows about handle will be able to do anything that alters it.


static would limit the scope to the current compile (the file). But it is a global declaration. The alternative is to pass the object around from function to function as a parameter. It's pretty common.

0

精彩评论

暂无评论...
验证码 换一张
取 消