最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

avr - Is there a way to create a static array in the .data section, where its length is calculated by the size of the .bss secti

programmeradmin0浏览0评论

I'm just wondering if there is a way I can tell the compiler that I want to create a static array inside the .data section of the Arduino's SRAM, where the array's size is calculated using the size of the .bss section.

It should technically be possible since the .bss is calculated at compile time.

I'm just wondering if there is a way I can tell the compiler that I want to create a static array inside the .data section of the Arduino's SRAM, where the array's size is calculated using the size of the .bss section.

It should technically be possible since the .bss is calculated at compile time.

Share Improve this question edited Jan 22 at 20:49 emacs drives me nuts 4,01218 silver badges40 bronze badges asked Jan 19 at 20:34 Logan SeeleyLogan Seeley 236 bronze badges 4
  • 3 For what reason would you want to do this? XY problem? – CPlus Commented Jan 19 at 21:37
  • ".bss is calculated at compile time." No. It's determined at link time by the linker/locator (at least with the GNU tools, which Arduino uses AFAIK). But better solve that XY problem. – emacs drives me nuts Commented Jan 21 at 11:56
  • @emacsdrivesmenuts You're right, I realized this after I made the post. A friend explained to me that a link-time optimization would be the only feasible way to implement what I am trying to do. – Logan Seeley Commented Jan 24 at 22:31
  • @CPlus Well I have a buffer, and it's size is calculated by the size of the heap. The heap's size will never change during runtime and therefore neither will my buffer. However, the heap's size does change during link-time depending on how many static variables exist. – Logan Seeley Commented Jan 24 at 22:33
Add a comment  | 

1 Answer 1

Reset to default 0

There is no way to do this in a standard compliant way since the C/C++ standard(s) know nothing about .bss or .data or their lengths.

One way is to allocate a respective data buffer on the heap (use malloc) or on the stack (use alloca). The overhead of alloca is less than that of malloc, but alloca'ted memory has only the lifetime of a similar auto variable.


Closest to the requested feature is to "allocate" an array buf[] after .bss like so:

extern char buf[] __asm("__heap_start");
extern char __bss_start[];
extern char __bss_end[];

int main (void)
{
  const size_t buf_size = __bss_end - __bss_start;
  memset (buf, 0, buf_size); // Clear buf[]
  buf[0] = 'A';              // Access buf[]
  ...

This is not compatible with malloc, which starts allocation at __heap_start. You can cater for that with:

  extern char *__malloc_heap_start;
  __malloc_heap_start += buf_size;

prior to the first call to malloc et al. (alloca is no issue).

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论