使用全局变量的最优雅方法是什么? [英] What is the most elegant way to work with global variables?

查看:162
本文介绍了使用全局变量的最优雅方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几年前,我了解到全局变量是不好的,应该避免。但是我知道它们有时是不可避免的,至少在嵌入式系统中是如此。您认为与他们合作的最优雅的方式是什么?

A couple years ago I learned that global variables are bad and should be avoided. But I know they are sometimes unavoidable, at least in an embedded system. What do you think is the most elegant way to work with them?

在我的项目中,我有一个名为 globals.h ,其中定义了所有全局变量:

In my projects I have a file called globals.h where I define all my global variables:

#ifndef GLOBALS_H
#define GLOBALS_H
extern int16_t    gVariable1;
extern int16_t    gVariable2;
….
#endif

在我的主项目文件中,我声明了所有全局变量:

In my main project file I declare all global variables:

/*
***********************************************************************
*                            global variables                         *
***********************************************************************
*/
    int16_t     gVariable1 = 0;
    int16_t     gVariable2 = 0;


int16_t main (void)
{
    gVariable1 = 6;

    //  do other stuff
}

知道我在需要访问全局变量的项目的每个其他文件中包含 globals.h

And know I include globals.h in every other file of the project which needs access to a global variable.

那很好,但是还有一种更优雅的方式来处理该问题吗?

That works fine, but is there a more elegant way to handle that?

推荐答案

我不确定全局变量在所有情况下都是不好的,但是您真的需要努力使它们很少(否则,您的代码不可读)。例如,< stdio.h> 具有 stdout ,如果将其替换为某些内容将不会更好。 FILE * get_standard_output(void); getter函数。

I am not sure that global variables are bad in all cases, but you really need to work hard to have very few of them (otherwise, your code in unreadable). For example <stdio.h> has stdout, and it won't be better if it was replaced by some FILE*get_standard_output(void); getter function.

根据经验,请避免超过4个或整个程序中的5个全局变量(将神奇数字7 称为提示(关于我们的认知限制)。

As a rule of thumb, avoid having more than 4 or 5 global variables in your entire program (recall the magical number seven as a hint on our cognitive limitations).

但是,您可以打包(巧妙并具有良好的品味,使代码易于阅读)几个相关的 全局变量转换为 struct 类型的单个变量。以您的示例为例,这可能意味着您的 globals.h

However, you could pack (cleverly and with good taste, to keep your code readable) several related global variables into a single one of struct type. With your example, that could mean in your globals.h:

struct globalstate_st { int16_t v1, v2; };

然后

extern struct globalstate_st gs;

,您应该使用 gs.v1 gVariable1 ;如果使用优化进行编译,则使用 gs.v1 的性能等同于使用 gVariable1

and you would use gs.v1 instead of gVariable1; if you compile with optimizations, the performance of using gs.v1 is equivalent to using gVariable1.

BTW,如果您有多线程程序,通常应该使用互斥体(或其他某种同步或原子性)。考虑阅读此pthread教程

BTW, if you have a multi-threaded program, you generally should protect global data with some mutex (or some other kind of synchronization or atomicity). Consider reading this pthread tutorial.

这篇关于使用全局变量的最优雅方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆