GCC,链接器脚本:解析为手动定义地址的变量?

时间:2015-04-15 16:20:20

标签: pointers gcc global-variables indirection

我将使用一个简单的具体示例来说明我正在尝试做的事情。

文件 main.c

#include <stdio.h>

unsigned int X;

int main()
{
    printf("&X = 0x%zX\r\n", &X);
    return 0;
}

我想知道是否有可能(使用链接器脚本/ gcc选项)在编译/链接时手动指定X的地址,因为我知道它位于内存中,位于我的可执行文件之外。

我只想知道这是否可行,我知道我可以使用指针(即unsigned int*)来访问特定的内存位置(r / w),但这不是我所追求的。

我所追求的是让GCC生成代码,其中 所有 访问全局变量/静态函数变量是通过间接级别完成的,即通过指针(-fPIC不够好,因为静态全局变量不能通过GOT访问)或者它们的地址可以手动指定(在链接/编译时)。

谢谢

1 个答案:

答案 0 :(得分:0)

What I'm after is making GCC generate code in which all accesses to global variables/static function variables … their addresses can be manually specified (at link/compile time).

You can specify the addresses of the .bss and .data sections (which contain the uninitialized and initialized variables respectively) with linker commands. The relative placement of the variables in the sections is up to the compiler/linker.

If you need only individual variables to be placed, this can be done by declaring them extern and specifying their addresses in a file, e. g. addresses.ld:

X = 0x12345678;

(note: spaces around = needed), which is added to the compiler/linker arguments:

cc main.c addresses.ld