Executing code before main()

前端 未结 5 416
执念已碎
执念已碎 2020-12-03 03:15

In object-oriented languages (C++) you can execute code before main() by using a global object or a class static object and have their constructors run the code

相关标签:
5条回答
  • 2020-12-03 03:23

    There are portable ways of specifying functions that can be executed "after" main is executed.

    1. atexit()

    2. at_quick_exit()

    Further, follow this link and about various types of initialization in C++ - that may be useful for you to execute code before main() is called.

    0 讨论(0)
  • 2020-12-03 03:39

    There are ways using __attribute__ but those are very specific to your compiler and code that is written using these are not really portable. On the other hand, the C language does not provide any start-up modules/libraries.

    In C, logically main() is the first function called by the OS. But before calling main(), the OS calls another function called start-up module to setup various environment variables, initialize (un-initialized) static variables, build a stack frame (activation record) and initialize the stack pointer to the start of the stack area and other tasks that have to be done before calling main().

    Say if you are writing code for embedded systems where there is no-or-minimal OS to do the above mentioned work, then you should explore these options which are compiler dependent. Other than GCC, Turbo-C and Microsoft C compilers provides facilities to add code in a particular hardware machine (f.e. 8086 machines).

    In other words, the start-up modules are not meant for the programmers.

    0 讨论(0)
  • 2020-12-03 03:39

    With gcc, you can do so by using the constructor function attribute, e.g.

    __attribute__ ((__constructor__)) 
    void foo(void) {
            ...
    }
    

    This will invoke foo before main.

    Note: This is probably not portable to other compilers.

    0 讨论(0)
  • 2020-12-03 03:40

    You can do it with __attribute__ ((constructor)). I've tested the following example with both gcc and clang. That being said, it's not part of the language.

    #include <stdio.h>
    
    void __attribute__ ((constructor)) premain()
    {
        printf("premain()\n");
    }
    
    int main(int argc, char *argv[])
    {
        printf("main()\n");
        return 0;
    }
    

    It does the following:

    $ ./test
    premain()
    main()
    

    GCC documents it at: https://gcc.gnu.org/onlinedocs/gcc-8.3.0/gcc/Common-Function-Attributes.html#Common-Function-Attributes

    0 讨论(0)
  • 2020-12-03 03:44

    You can initialize global variables but not call functions within these initializations.

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