Make GCC initialize global variables generating instructions in crti.S _init

William Tambe tambewilliam@gmail.com
Mon Jan 6 04:59:00 GMT 2020


As illustrated in the example below, when initializing a global
variable using a symbol reference, GCC generates .quad assembly
statement; and when initializing a local variable using a symbol
reference, GCC generates instructions.

Is there a way to make GCC generate instructions within the crti.S
_init function to initialize a global variable, instead of generating
.long or .quad assembly statement ?
The idea being to make GCC generate instructions to initialize a
global variable, just like it generates instructions to initialize a
local variable.

Example for illustrating GCC default initialization behavior when
initializing global variable myglobal and local variable mylocal:

    void myfunc (void) {}
    void *myglobal = myfunc;
    void main (void) {
            void *mylocal = myfunc;
    }

GCC generates the following assembly:

            .text
            .globl  myfunc
            .type   myfunc, @function
    myfunc:
            pushq   %rbp    #
            movq    %rsp, %rbp      #,
    # test.c:1: void myfunc (void) {}
            nop
            popq    %rbp    #
            ret
            .size   myfunc, .-myfunc
            .globl  myglobal
            .section        .data.rel.local,"aw",@progbits
            .align 8
            .type   myglobal, @object
            .size   myglobal, 8
    myglobal:
            .quad   myfunc
            .text
            .globl  main
            .type   main, @function
    main:
            pushq   %rbp    #
            movq    %rsp, %rbp      #,
    # test.c:4:    void *mylocal = myfunc;
            leaq    myfunc(%rip), %rax      #, tmp87
            movq    %rax, -8(%rbp)  # tmp87, mylocal
    # test.c:5: }
            nop
            popq    %rbp    #
            ret
            .size   main, .-main



More information about the Gcc-help mailing list