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.
- 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
1 Answer
Reset to default 0There 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).