问题
I want to take the symbols in the .data
section generated for a particular C file and place them in a different section (e.g. .mydata
) in the final executable. For example,
normaldata.c: char * my_str = "this should appear in .data";
specialdata.c: char * my_special_str = "this should appear in .mydata";
By default, both my_str
and my_special_str
appear in the .data
section. However, when I generate specialdata.o
, I want to send anything that would have appeared in .data
instead to .mydata
.
I am aware that I can use the __attribute__((section(".mydata")))
to achieve this effect, but I don't know how to apply this to a designated initializer of pointer member of a struct (I have simplified my code for this question). So instead, I'm thinking maybe I can use a linker script and send all the data from a particular file into my special section.
I tried this linker script (link.lds
):
SECTIONS
{
.mydata : { *(.data) }
}
with gcc -c specialdata.c -T link.lds -o specialdata.o
, but the output of objdump -x specialdata.o
shows a .data
section but no .mydata
section.
What am I doing wrong?
回答1:
In your C declaration, the section()
attribute specifies an input section name for the linker. The .mydata
name, specified in the SECTIONS
part of the linker script is the name of an output section. In .mydata
you tell the linker to place all the symbols from the "*(.data)
" input sections into the .mydata
output section, but your C attribute uses the name of the output section.
To get the linker to place the C variable in the correct output section, you must use the same name for the input sections in both the .mydata
output section definition and the C section()
attribute.
Try changing the name of the input section and using teh same name in both the linker script and the C attibutes.
Linker script:
SECTIONS
{
/* Put all symbols from the .my_data input section into the
* .mydata output section.
*/
.mydata : { *(.my_data) }
}
specialdata.c source:
// Note that the input section name is ".my_data", not ".mydata".
char * my_special_str __attribute__((section(".my_data"))) =
"this should appear in .mydata";
来源:https://stackoverflow.com/questions/28444361/c-send-data-to-a-different-section