内存与ld和ar命令重叠

时间:2012-11-30 11:43:47

标签: gcc compilation ld ar hardcoded

我已使用此命令链接了一些文本文件:

  

ld -r -b binary -o resources1.o * .txt

我得到一个文件resources.o,内容如下:

  

nm resources1.o

00000018 D _binary_texto4_txt_end
00000018 A _binary_texto4_txt_size
00000000 D _binary_texto4_txt_start
00000031 D _binary_texto5_txt_end
00000019 A _binary_texto5_txt_size
00000018 D _binary_texto5_txt_start
0000004a D _binary_texto6_txt_end
00000019 A _binary_texto6_txt_size
00000031 D _binary_texto6_txt_start

我有其他的resources2.o文件来自另一个ld命令,但它有不同的内容:

00000018 D _binary___textos1_texto1_txt_end
00000018 A _binary___textos1_texto1_txt_size
00000000 D _binary___textos1_texto1_txt_start
00000031 D _binary___textos1_texto2_txt_end
00000019 A _binary___textos1_texto2_txt_size
00000018 D _binary___textos1_texto2_txt_start
0000004a D _binary___textos1_texto3_txt_end
00000019 A _binary___textos1_texto3_txt_size
00000031 D _binary___textos1_texto3_txt_start

我想将两个resources.o文件合并到一个libSum.a文件中。所以我使用这个命令:

  

ar rvs libSum.a resources1.o resources2.o

当我将libSum.a链接到我的C程序并尝试使用这些文本时,我不能忘记他们共享相同的内存偏移量。所以 binary __ textos1_texto1_txt_start的方向与_binary_texto4_txt_start(0X00000000)相同。

如何将两个资源文件组合在一个.a lib中,避免内存偏移重叠? 感谢

1 个答案:

答案 0 :(得分:0)

文件内容存在愚蠢的错误。它们是具有不同名称的同一文件(复制和粘贴错误),因此在显示其内容时,它似乎是内存偏移错误。

到现在为止,我正在使用下一个脚本来编译“libResources.a”库中的所有资源:

rm libResources.a
rm names.txt

basedir=$1
for dir in "$basedir"/*; do
    if test -d "$dir"; then
    rm "$dir"/*.o
    ld -r -b binary -o "$dir"/resources.o "$dir"/*
    nm "$dir"/resources.o >> names.txt
    fi
done

for dir in "$basedir"/*; do
    if test -d "$dir"; then
    ar q libResources.a "$dir"/*.o
    fi
done

要测试我的硬编码资源,我使用以下C代码:

/*
 ============================================================================
 Name        : linkerTest.c
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>

extern char _binary___textos1_texto1_txt_start[];
extern char _binary___textos1_texto1_txt_end[];

extern char _binary___textos2_texto4_txt_start[];
extern char _binary___textos2_texto4_txt_end[];

int main(void) {
    int i;
    int sizeTexto1 = _binary___textos1_texto1_txt_end - _binary___textos1_texto1_txt_start;
    int sizeTexto4 = _binary___textos2_texto4_txt_end - _binary___textos2_texto4_txt_start;


    for (i=0;i<sizeTexto1;i++){
        putchar(_binary___textos1_texto1_txt_start[i]);
    }

    for (i=0;i<sizeTexto4;i++){
        putchar(_binary___textos2_texto4_txt_start[i]);
    }

    return EXIT_SUCCESS;
}

如果您想测试我的示例,请不要忘记在项目中链接文件“libResources.a”。