首页 > 解决方案 > Should I redeclare a part of an external array for the use in a module

问题描述

Let's say I have thre project wide variable blocks with external linkage vByte[1000], vWord[1000] and vQword[1000]. And because of the lack of a better debug solution, every variable that I want to see at runtime has to be in those blocks.

Now I want to implement a set of functions in a module(compilation unit) that has a few important values that I want to be able to monitor. I came up with the following solutions to make a more clear access to these parts of the array, but I am unsure which to use.

At first I would declare the array extern vByte[1000]; in my module and the I would like to give a specific variable of the array a fitting name.

I could just #define the variables I want to use: #define importantValue1 vByte[21] and use them like this.

But I think it might be better to encapsulate the variable in my module, maybe like this:

static byte *importantValue1 = &vByte[21]; 

This would reinforce that this variable is for use in this module. Are there drawbacks to this or is the define just the straight forward approach with less overhead and no drawbacks?

标签: cc89

解决方案


一般来说,很难回答是 a#define还是指针是更好的方法。

然而,从减少依赖关系和代码复杂性的角度来看,减少全局变量的数量通常会减少函数/单元之间的依赖关系,从而降低整体复杂性。

所以我想说这不是#define- 还是指针方法更好的问题。我宁愿争取不访问这些全局数组的函数(不管通过哪种“变量”技术),而是只使用函数参数/参数。

顺便说一句:注意#define-"variable" 和指针变量需要以不同的方式使用,因为在第一种情况下你可以 write importantValue1 = 10,而在第二种情况下你必须 write *importantValue1 = 10。但我想你已经意识到了这一点。


推荐阅读