为什么全局变量坏,在单线程的,非操作系统,嵌入式应用 [英] Why are global variables bad, in a single threaded, non-os, embedded application

查看:196
本文介绍了为什么全局变量坏,在单线程的,非操作系统,嵌入式应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数我看到使用全局变量的反对的意义,因为它们是指多个线程,线程安全,等等。

Most of the objections I see to using global variables make sense since they refer to issues of multiple threads, thread safety, etc.

但在一个小的,单线程的,非操作系统,情况下,你有什么异议?就我而言,我写在C我的嵌入式系统,如果它很重要。我还对产品的唯一开发商。

But in a small, single threaded, non-OS, case, what objections do you have? In my case, I'm writing my embedded system in "C", if it matters. I'm also the only developer on the product.

为什么会消除全局变量让我的code更好?

Why would eliminating global variables make my code better?

(读取多个答复后,我意识到我应该也指出,这一系统没有动态内存分配(例如malloc的),所有的记忆是在编译时静态分配。)

(After reading several responses, I realize I also should have pointed out that this system has no dynamic memory allocation (e.g. malloc). All the memory is statically allocated at compile time.)

推荐答案

不会。

全局变量的两个基本问题简直是混乱的命名空间,任何人已经控制了他们的事实(因此,潜在的冲突和多线程冲突)。

The two fundamental issues with global variables is simply cluttering the namespace, and the fact that "no one" has "control" over them (thus the potential collisions and conflict with multiple threads).

在全局是坏,像pretty很多其他每台计算机的编程方法是一个准则,而不是硬性规定。当这些各种规则制成,其最好的,而不是简单地死记硬背采用规则,了解创建规则落后的情况和动机。不要只是把他们盲目。

The "globals are bad", like pretty much every other computer programming idiom is a guideline, not a hard and fast rule. When these kinds of "rules" are made, its best rather than simply adopting the rule by rote to understand the circumstances and motivations behind the creation of the rule. Don't just take them blindly.

在你的情况,你似乎明白你的系统的性质和周围的规则的论据,并决定它不适用于这种情况。你说得对,没有。

In your case, you seem to understand the nature of your system and the arguments around the rule and decided that it doesn't apply in this case. You're right, it doesn't.

所以,不要担心。

这篇关于为什么全局变量坏,在单线程的,非操作系统,嵌入式应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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