如何使用 avr-gcc 在 C/C++ 中执行预主初始化? [英] How can I perform pre-main initialization in C/C++ with avr-gcc?
问题描述
为了确保一些初始化代码在 main
(使用 Arduino/avr-gcc)之前运行,我有如下代码:
In order to ensure that some initialization code runs before main
(using Arduino/avr-gcc) I have code such as the following:
class Init {
public:
Init() { initialize(); }
};
Init init;
理想情况下,我希望能够简单地编写:
Ideally I'd like to be able to simply write:
initialize();
但这不能编译...
有没有更简洁的方法来达到同样的效果?
Is there a less verbose way to achieve the same effect?
注意:代码是Arduino草图的一部分,所以main
函数是自动生成的,不能修改(例如调用initialize
在任何其他代码之前).
Note: the code is part of an Arduino sketch so the main
function is automatically generated and cannot be modified (for example to call initialize
before any other code).
更新: 理想情况下,初始化将在 setup
函数中执行,但在这种情况下,还有其他代码依赖于它发生在 main之前代码>.
Update: ideally the initialization would be performed in the setup
function, but in this case there is other code depending on it which occurs before main
.
推荐答案
你可以使用 GCC 的 constructor
属性 以确保它在main()
之前被调用:
You can use GCC's constructor
attribute to ensure that it gets called before main()
:
void Init(void) __attribute__((constructor));
void Init(void) { /* code */ } // This will always run before main()
这篇关于如何使用 avr-gcc 在 C/C++ 中执行预主初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!