Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

How to get the location of a section in C code

In the linker script, I have defined

MEMORY {
  sec_1 : ORIGIN = 0x1B800, LENGTH = 2048
  ......
}

How can I read the start address of this section in C? I would like to copy it in a variable in the C code

question from:https://stackoverflow.com/questions/65846716/how-to-get-the-location-of-a-section-in-c-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically to achieve this, you have two tasks to fulfill:

  1. Tell the linker to save the start address of the section. This can be achieved by placing a symbol in the linker script at the beginning of your section.
  2. Tell the compiler to save initialize a constant with an address filled in later by the linker

As for the first step: In your section sec_1 you have to place a symbol that will be placed at the start of that section:

SECTIONS
{
    ...
    .sec_1 : 
    {
        __SEC_1_START = ABSOLUTE(.); /* <-- add this */
        ...
    } > sec_1
    ...
}

Now that the linker produces bespoke symbol, you have to make it accessible from the compiler side. In order to do so, you need somewhere some code like this:

/* Make the compiler aware of the linker symbol, by telling it, there 
   is something, somewhere that the linker will put together (i.e. "extern") */
extern int __SEC_1_START;

void Sec1StartPrint(void) {
    void * const SEC_1_START = &__SEC_1_START;
    printf("The start address for sec_1 is: %p", SEC_1_START);
}

By calling Sec1StartPrint() you should get an address output that matches your *.map file the linker created.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...