您的位置:首页 > 其它

将一个普通文件的内容链接到可执行程序中

2014-02-10 15:55 351 查看
有时候,我们可能需要将一个普通文件的内容,链接到可执行程序中。

本文就来说说如何实现这个目标。

我们将制作一个简单的hello_world可执行程序,该程序中包含了另一个文件haha.txt的内容,hello_world程序运行后将打印他所包含的文件haha.txt的内容。

其中,haha.txt内容如下:

I am a file who will be linked into a exe file.

注意,本文之所以用文本文件haha.txt,仅仅是为了便于说明问题。

实际上,本文的方法适用于将任意类型的文件链接到可执行程序中。

好了,现在就来看看具体的实现方法。

首先交待一下,我们接下来的工作,所用到的全部文件,全部位于同一个目录下。

这个目录,就是我们的工作目录。

我们所执行的所有命令,也都是在此目录下执行的。

一. 创建haha.o

haha.o是elf文件,创建他的目的,就是为了将他作为一个容器,用以包含haha.txt的内容。这样好和后面的hello_world.o进行链接。

创建haha.o的过程如下:

a)创建一个汇编语言源文件haha.S。

如果是Linux平台,gcc工具链,则内容如下:

.section .data

.globl
file_data_begin

.align 32

.type file_data_begin, @object

.size file_data_begin, file_data_end-file_data_begin

file_data_begin:

.incbin
"./haha.txt"

.globl
file_data_end

.align 1

.type file_data_end, @object

.size file_data_end, 0

file_data_end:

如果是windows平台,mingw工具链,[b]则内容如下:[/b]

.globl
_file_data_begin

.data

.align 32

_file_data_begin:

.incbin
"./haha.txt"

.globl
_file_data_end

.data

.align 1

_file_data_end:

.space 0





b) 编译haha.S生成haha.o

gcc -c haha.S

二、创建hello_world.o

a)创建一个C源文件hello_world.c,内容如下:

#include <stdio.h>

#include <string.h>

extern char file_data_begin[];

extern char file_data_end[];

int main(int argc, char *argv[])

{

int data_len = file_data_end - file_data_begin;

char data_tmp[data_len+1];

memcpy(data_tmp, file_data_begin, data_len);

data_tmp[data_len]=0;

printf("I contais a file with %d bytes data\n", data_len);

printf("its contents is as bellow:\n %s", data_tmp);

return 0;

}


b) 编译hello_world.c生成[b]hello_world.o[/b]

gcc -c hello_world.c

三、生成最终的hello_world.exe
gcc -o hello_world.exe hello_world.o haha.o

四、运行效果

# ./hello_world.exe

I contais a file with 47 bytes data

its contents is as bellow:

I am a file who will be linked into a exe file.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐