How can I allocate data or function or a section to a fixed address?

To place an output section at a specific address, you have to apply the address in the section definition of the linker script file, for example:

SECTIONS
{
    .mydata 0xd0001040 :
	{
		*(.mydata*)
	} > MYRAMX
}

The example instructs the linker to put all input sections, from all input object files, containing .mydata* into the output section .mydata, and locate this section at the address 0xd0001040. If you want to locate only the input sections of some object files in the output section, you can exchange the wildcard '*' with another wildcard to match the specific object file name(s) and/or path. For example:

SECTIONS
{
	.mydata 0xd0001040 :
	{
		*test.o(.mydata*)
	} > MYRAMX
}

This will match the object files with *test.o in their filename and path.

Input sections can be defined in the code using pragmas:

#pragma clang section data=".mydata"
static int my_var1 = 5;
#pragma clang section data=""

Another possibility is to use the compiler option -ffunction-sections to tell the compiler to define a section for each function. The compiler will name the section .text.<functionname>. Please note the corresponding option -fdata-sections for data.

To locate a function at a specific address you can follow the earlier example. You can also add the object file name in the linker script command, like in the previous example.

A related solution is to define a memory region at the desired address. That is, writing the specific address in the memory region instead of the output section, for example:

MEMORY
{
  my_region1 (rx):  origin = <addr>, length = <len>
}