V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zhng920823
V2EX  ›  C

将资源嵌入到可执行文件中并保持目录结构

  •  
  •   zhng920823 · 102 天前 · 1245 次点击
    这是一个创建于 102 天前的主题,其中的信息可能已经有所发展或是发生改变。

    保持目录结构可以方便根据路径查找使用.

    • bash 脚本用来生成 .c 文件
    chmod +x embed_file_c.sh
    
    ./embed_file_c.sh dir2c_test
    # or
    ./embed_file_c.sh dir2c /path/to/resource > _data_enc.c
    gcc embed_file.c -o embed_file
    ./embed_file
    
    • 生成的 .c 文件这样使用
    #include <stdio.h>
    #include <stdint.h>
    int main(int argc, char *argv[]) {
    	#define _DATA_ENC_INC 1
    	#include "_data_enc.c"
    	for (int i = 0; i < sizeof(_data_enc_lst)/sizeof(_data_enc_lst[0]); ++i) {
    		printf("%3u, %3u, %s\n", _data_enc_lst[i].off, _data_enc_lst[i].len, _data_enc_lst[i].path);
    		// &_data_enc[_data_enc_lst[i].off] is the data ptr, use it by need
    	}
    	return 0;
    }
    

    代码 https://github.com/webd90kb/webd/tree/master/codes/scripts/embed_file_c

    6 条回复    2024-07-09 11:24:17 +08:00
    w568w
        1
    w568w  
       101 天前
    单就前一个需求(嵌入资源),C23 已经标准化了: https://zh.cppreference.com/w/c/preprocessor/embed
    zhng920823
        2
    zhng920823  
    OP
       101 天前
    @w568w 原理基本一样的. 我这脚本可以嵌入目录
    lixile
        3
    lixile  
       101 天前
    大文件 编译时间太长了
    objcopy 直接转换为.o 才更合理
    zhng920823
        4
    zhng920823  
    OP
       101 天前
    @lixile 实在太大的文件就外置了
    codehz
        5
    codehz  
       101 天前
    其实可以直接 zip 塞可执行文件末端,然后运行时打开自己这个程序的文件,读取即可
    而且由于 zip 的特性(末端识别),这样构造出来的文件可以直接用 zip 程序附加新文件,或者用 unzip 解压()
    zhng920823
        6
    zhng920823  
    OP
       101 天前
    @codehz #4 这个办法好, 方便别人修改资源
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3377 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 04:43 · PVG 12:43 · LAX 21:43 · JFK 00:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.