GCC: how to tell GCC to put the 'main' function at the start of the .text section?

前端 未结 3 380
清歌不尽
清歌不尽 2020-12-16 02:04

I\'ve just started learning some ARM programming and I\'ve got stuck in a slightly annoying problem. The toolchain I\'m using to compile my sources is Sourcery CodeBench Lit

相关标签:
3条回答
  • 2020-12-16 02:42

    Solved the problem. For whoever faces it:

    • When compiling with GCC, add the -ffunction-sections option in the command-line. This will tell GCC to put each function in a separate section. The format of the section name will be .text.#function name#, without the # (that is, if the function belongs to the .text section [ which by default is true ]).
    • Secondly, use a linker script to order these "function-sections" into the final big .text section. As an example, putting the main function at the beginning of the .text section would result in an LD script that looks approximately like this:

      ENTRY(main)
      SECTIONS
      {
          .text :
          {
              *(.text.main);
              *(.text*);
          }
      }
      
    0 讨论(0)
  • 2020-12-16 03:03

    You can also just put 'main' in its own section using an __attribute__:

    int main (void) __attribute__ ((section ("entry")));
    

    and then in the ld file:

    ENTRY(main)
    SECTIONS
    {
        .text :
        {
            *(main)
            *(.text)
        }
    }
    

    There are plenty of other interesting __attributes__, read more about them here: http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

    0 讨论(0)
  • 2020-12-16 03:06

    First, see how is the .text section defined in your gcc's default linker script (so you don't have to make your own), by calling it as:

    gcc -Wl,-verbose
    

    that will print out the default linker script. Mine shows this for the .text section:

    /* text: Program code section */
      .text : 
      {
        *(.text)
        *(.text.*)
        *(.gnu.linkonce.t.*)
      }
    

    So in order to have the "main" function be the first in the .text section (and the rest be contiguous), you have to set the "section" attribute for all other functions. For example:

    void main(void);
    void funct1(....) __attribute__ ((section (".text.A")));
    void funct2(....) __attribute__ ((section (".text.A")));
    void funct3(....) __attribute__ ((section (".text.A")));
    

    It's enough with "attributing" the function prototypes. That way, when you compile now, the "main" function will be the first one in the ".text" section and all others will follow on the immediately consecutive addresses.

    If you want to place the ".text" section (i.e. "main" function) at a specific address (for example 0x1000), remember to link with:

    gcc .... -Wl,-Ttext=0x1000
    
    0 讨论(0)
提交回复
热议问题