英文:
Why are pin definitions in Arduino declared static
问题
在Arduino代码库中,不同兼容板的引脚定义存储在名为pins_arduino.h的文件中,每个板都有不同的版本。
引脚编号在头文件中声明和初始化,例如:
static const uint8_t A0 = 14;
有两件事让我感到惊讶:首先,他们会在头文件中初始化变量 - 这不是我被教导的良好实践。其次,他们会将它们声明为静态变量,在标准C++中,这会在包括该文件的每个翻译单元中创建一个单独的变量 - 这似乎在内存受限的设备上使用内存不当。
是否有人可以解释为什么会这样做,而不是在头文件中声明引脚为extern,然后在cpp文件中初始化它们呢?使用这种声明方法是否有优势?
谢谢
詹姆斯
英文:
In the Arduino codebase the definitions of the pins of the different compatible boards are stored in a file called pins_arduino.h, with a different version for each board.
The pin numbers are both declared and initialized in the header files for example:
static const uint8_t A0 = 14;
Two things surprised me about this: first that they would initialize a variable in the header - which I was taught not good practice. And second that they would declare them static, which in standard C++ would create a separate variable in each translation unit which included the file - seems like poor memory use in a memory restricted device.
Could anyone shed any light on why it was done like this and not, for example, declaring the pins extern in the header and then initializing them in a cpp file? Are there advantages to the declaration method used?
Thanks
James
答案1
得分: 3
首先,他们会在头文件中初始化一个变量 - 这不是一个好的做法,我被教导应该避免这样做。
在头文件中定义变量可能会违反单一定义规则。将它们声明为static
可以解决这个问题。
在标准C++中,会在包含该文件的每个翻译单元中创建一个单独的变量 - 在内存受限的设备上似乎会浪费内存。
如果使用了内联,不会使用内存。这些变量只有在需要获取它们的地址时才会占用内存,但这是对这些变量的不寻常使用。
有人能解释为什么要这样做,而不是在头文件中将引脚声明为extern,然后在cpp文件中初始化吗?
如果将变量定义在一个单独的cpp文件中,编译器将难以将这些值内联到另一个cpp文件中。
英文:
> first that they would initialize a variable in the header - which I was taught not good practice.
Defining a variable in a header can break the One Definition Rule. Declaring them as static
resolves this.
> in standard C++ would create a separate variable in each translation unit which included the file - seems like poor memory use in a memory restricted device.
If the usage is inlined, no memory is used. These variables would need to occupy memory if you took their addresses, but that would be an unusual usage of these variables.
> Could anyone shed any light on why it was done like this and not, for example, declaring the pins extern in the header and then initializing them in a cpp file?
If the variables were defined in a single cpp file, the compiler would have difficulty inlining the values in a different cpp file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论