如何定义一个内存区域以在编译时在链接器脚本和 C 代码中使用?

问题描述 投票:0回答:1

我的链接器脚本中有以下内容:

...

_other_start   = ORIGIN(OTHER);
_other_end     = ORIGIN(OTHER) + LENGTH(OTHER);
_other_size    = LENGTH(OTHER);

...

/* Memories definition */
MEMORY
{
  ...
  OTHER    (rw)    : ORIGIN = 0xC000000,   LENGTH = 1MB
  ...
}

...

我有以下 C 代码:

void fun() {
  extern char _other_start;
  char *ptr = &_other_start
  char tmp[10];

  for(int i = 0; i < 10; i++) {
    tmp[i] = *ptr++;
  }
}

使用 gcc 编译器进行编译时,出现以下警告:

warning: '__builtin_memcpy' reading 10 bytes from a region of size 1 [-Wstringop-overflow=]
。这个警告乍一看是有道理的,我必须将其静音的唯一方法是重写我的函数,如下所示:

void fun() {
  extern char _other_start[10];
  char *ptr = &_other_start
  char tmp[10];

  for(int i = 0; i < 10; i++) {
    tmp[i] = *ptr++;
  }
}

我的问题是,我是否可以以某种方式在编译时定义

extern char _other_start
缓冲区的大小,与链接器脚本中定义的内存区域的大小完全相同,而不必在宏中复制链接器脚本中的值?类似这样的东西:

#define OTHER_SIZE = 1024 * 1024 // I don't want this, it's code duplication.
#define OTHER_SIZE = _other_size // I want to use the value from the linker script, but I know like that it does not work.

void fun() {
  extern char _other_start[OTHER_SIZE];
  char *ptr = &_other_start
  char tmp[10];

  for(int i = 0; i < 10; i++) {
    tmp[i] = *ptr++;
  }
}
c linker gnu
1个回答
0
投票

您需要更改该伪对象的类型。

void fun() {
  extern char _other_start[];
  char *ptr = _other_start;
  char tmp[10];

  for(int i = 0; i < 10; i++) {
    tmp[i] = *ptr++;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.