如何获取C代码中某个节的位置

1 c

在链接描述文件中,我定义了

MEMORY {
  sec_1 : ORIGIN = 0x1B800, LENGTH = 2048
  ......
}
Run Code Online (Sandbox Code Playgroud)

在C语言中如何读取本节的起始地址?我想将它复制到C代码中的变量中

jun*_*nix 5

基本上要实现这一目标,您需要完成两项任务:

  1. 告诉链接器保存该节的起始地址。这可以通过在节的开头的链接描述文件中放置一个符号来实现。
  2. 告诉编译器保存初始化常量并使用链接器稍后填充的地址

至于第一步:在您的部分中,sec_1您必须放置一个符号,该符号将放置在该部分的开头:

SECTIONS
{
    ...
    .sec_1 : 
    {
        __SEC_1_START = ABSOLUTE(.); /* <-- add this */
        ...
    } > sec_1
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在链接器生成了定制符号,您必须使其可以从编译器端访问。为了做到这一点,你需要一些像这样的代码:

/* 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);
}
Run Code Online (Sandbox Code Playgroud)

通过调用,您应该获得与链接器创建的文件Sec1StartPrint()相匹配的地址输出。*.map