对两个文件使用相同的链接器 ld 脚本文件目标

using the same linker ld script file target for two files

假设我有一个如下所示的内存分配:

MEMORY
{
    firstfile  : ORIGIN = 0x00000000, LENGTH = 0x2000 
    secondfile : ORIGIN = 0x00002000, LENGTH = 0x6000
}

现在我想对两个不同的文件使用相同的 ld 脚本。 'firstfile.c' 和 'secondfile.c' 如何让第一个文件 entire 分配在 'firstfile' 部分下,第二个文件在 'secondfile' 部分下?

目前 .text 都在 secondfile 部分。 在 firstfile.c 中的每个函数上使用特殊属性部分无济于事

在您的链接描述文件片段中 firstfilesecondfileMEMORY 区域而不是 SECTIONS,因此部分属性将(我猜)被忽略,因为这些部分确实不存在。

您必须创建 MEMORY 区域,在其中放置 SECTIONS,然后将目标代码中定义的部分分配给链接描述文件中声明的部分。请注意,找到的是 目标代码 ,而不是源文件 - 链接器对源文件一无所知:

类似于:

MEMORY
{
    FIRST_MEMORY  : ORIGIN = 0x00000000, LENGTH = 0x2000 
    SECOND_MEMORY : ORIGIN = 0x00002000, LENGTH = 0x6000
}

SECTIONS
{
  .firstsection :
  {
    . = ALIGN(4);

    *firstfile.o (.text .text*)   /* Locate firstfile text sections here */

  } > FIRST_MEMORY

  .secondsection :
  {
    . = ALIGN(4);

    *secondfile.o (.text .text*)  /* Locate secondfile text sections here */

  } > SECOND_MEMORY
}

然后您可以将任意数量的模块明确定位到每个部分。

您可能需要一个默认位置来放置未明确定位的模块。在这种情况下,您应该添加:

*(.text)           /* .text sections (code) */
*(.text*)          /* .text* sections (code) */

到其中一个部分(或创建一个单独的默认 .text 部分)。

此外,如果您添加:

*(.firstsection*)  /* Locate anything with firstsection attribute here */

*(.secondsection*) /* Locate anything with secondsection attribute here */

到相应的部分,您可以使用代码中的 __section__ 属性将特定函数(或数据)定位到这些部分,就像您之前尝试的那样。但是最好定位整个模块,因为它不需要修改和维护代码。