首页 > 其他 > 详细

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

时间:2014-02-10 17:11:57      阅读:243      评论:0      收藏:0      [点我收藏+]

有时候,我们可能需要将一个普通文件的内容,链接到可执行程序中。

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


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


其中,haha.txt内容如下:

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


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

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


好了,现在先来看看Linux下的实现方法。


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

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

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


一. 创建haha.o

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

创建haha.o的过程如下:

a)创建一个汇编语言源文件haha.S,内容如下:

.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:


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生成hello_world.o

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.


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

原文:http://blog.csdn.net/crazycoder8848/article/details/19038885

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!