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

后端 未结 9 2004
名媛妹妹
名媛妹妹 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:15

    Sure, you put this in one of your your header files, say preinit.h:

    class Init { public: Init() { initialize(); } }; Init init;
    

    and then, in one of your compilation units, put:

    void initialize(void) {
        // weave your magic here.
    }
    #include "preinit.h"
    

    I know that's a kludge but I'm not aware of any portable way to do pre-main initialization without using a class constructor executed at file scope.

    You should also be careful of including more than one of these initialization functions since I don't believe C++ dictates the order - it could be random.

    I'm not sure of this "sketch" of which you speak but would it be possible to transform the main compilation unit with a script before having it passed to the compiler, something like:

    awk '{print;if (substr($0,0,11) == "int main (") {print "initialize();"};}'
    

    You can see how this would affect your program because:

    echo '#include 
    int main (void) {
        int x = 1;
        return 0;
    }' | awk '{
        print;
        if (substr($0,0,11) == "int main (") {
            print "    initialize();"
        }
    }'
    

    generates the following with the initialize() call added:

    #include 
    int main (void) {
        initialize();
        int x = 1;
        return 0;
    }
    

    It may be that you can't post-process the generated file in which case you should ignore that final option, but that's what I'd be looking at first.

提交回复
热议问题