首页 > 解决方案 > 如何在 C 代码中获取部分的位置

问题描述

在链接器脚本中,我定义了

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

如何在 C 中读取此部分的起始地址?我想将它复制到 C 代码中的变量中

标签: c

解决方案


基本上要实现这一点,您有两个任务要完成:

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

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

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

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

/* 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);
}

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


推荐阅读