How can I perform pre-main initialization in C/C++ with avr-gcc?

后端 未结 9 1964
名媛妹妹
名媛妹妹 2020-12-28 09:21

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         


        
相关标签:
9条回答
  • 2020-12-28 10:19

    You can use the ".init*" sections to add C code to be run before main() (and even the C runtime). These sections are linked into the executable at the end and called up at specific time during program initialization. You can get the list here:

    http://www.nongnu.org/avr-libc/user-manual/mem_sections.html

    .init1 for example is weakly bound to __init(), so if you define __init(), it will be linked and called first thing. However, the stack hasn't been setup, so you have to be careful in what you do (only use register8_t variable, not call any functions).

    0 讨论(0)
  • 2020-12-28 10:22

    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()
    
    0 讨论(0)
  • 2020-12-28 10:22

    There is how I perform pre-main coding. There are sever init sections executed before main, refers to http://www.nongnu.org/avr-libc/user-manual/mem_sections.html initN sections.

    Anyhow, this only works on -O0 optimization for some reason. I still try to find out which option "optimized" my pre-main assembly code away.

    static void
    __attribute__ ((naked))
    __attribute__ ((section (".init8")))    /* run this right before main */
    __attribute__ ((unused))    /* Kill the unused function warning */
    stack_init(void) {assembly stuff}
    

    Update, it turns out I claimed this function is unused, leading to optimize the routine away. I was intended to kill function unused warning. It is fixed to used used attribute instead.

    0 讨论(0)
提交回复
热议问题