Reputation: 753
If I use the __attribute__(section(".section_i"))
, the variable is treated as an initialized variable.
Let's take a quick look at the following example(declared as global variable):
static unsigned char array[1024] __attribute__((section (".section_i")));
The above declaration will increase the data size by 1k even though I have not initialized the array. How can I mark the variable as not initialized to avoid the increasing of data section?
Upvotes: 0
Views: 2189
Reputation: 140540
static unsigned char array[1024] __attribute__((section (".section_i")));
The above declaration will increase the data size by 1k even though I have not initialized the array. How can I mark the variable as not initialized to avoid the increasing of data section?
OK, this is not actually about "initialized" or "not initialized"; this is about whether or not the variable is treated as "common", not requiring preallocated space in the data segment of the executable image. (Unlinked object files have sections; fully linked executables and shared libraries have segments.)
https://gcc.gnu.org/onlinedocs/gcc-7.3.0/gcc/Common-Variable-Attributes.html#Common-Variable-Attributes says that this is controlled with the "common" attribute, so
static unsigned char array[1024] __attribute((section(".section_i"), common));
is documented to do what you want (provided that your linker script cooperates; the section named .section_i
must be put into the appropriate segment; for historical reasons, the name of that segment is probably "BSS"). However, when I actually try that with the compiler I have to hand (which is indeed GCC 7.3, native compiler for x86_64-Linux) it generates assembly language that might not do the right thing. You should try it with your compiler anyway; it is probable that this is just a plain old bug in the x86-64 back end, and one that may not be duplicated in the back end for whatever embedded environment you're working with.
Note that you should inspect a fully linked executable image before concluding that this does not work. It's possible that the variable will take up space in the object file that defines it, but not in the executable.
For incredibly stupid reasons that I regret I even know about and do not want to attempt to explain, it may also help to call the section .bss.section_i
instead of just .section_i
. This may also make it easier to write the linker script.
Upvotes: 3