文章目录
- 1 背景
- 2 交叉编译流程
- 2.1 下载源码
- 2.2 编译
- 2.3 测试代码
- 2.4 交叉编译app程序
- 2.5 压缩及效率测试
1 背景
需要再app中使用压缩算法,不能直接移植gzip,gzip交叉编译得到gzip,应该使用libz代码
进行编译生成libz库.
2 交叉编译流程
2.1 下载源码
zlib-1.3.1 解压
2.2 编译
执行编译生成 makefile
CC=aarch64-linux-gnu-gcc ./configure -shared --prefix=/home/xhome/opt/opt_lib
编译
make
安装
make install
2.3 测试代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zlib.h"#define BUFFER_SIZE 4096void compress_data(const char *input_data, int input_size, char *output_data, int *output_size) {z_stream strm;int ret;// 初始化z_stream结构memset(&strm, 0, sizeof(strm));strm.zalloc = Z_NULL;strm.zfree = Z_NULL;strm.opaque = Z_NULL;// 设置压缩级别为默认值ret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);if (ret != Z_OK) {fprintf(stderr, "压缩初始化失败\n");exit(EXIT_FAILURE);}// 设置输入数据strm.avail_in = input_size;strm.next_in = (Bytef *)input_data;// 设置输出数据strm.avail_out = *output_size;strm.next_out = (Bytef *)output_data;// 执行压缩ret = deflate(&strm, Z_FINISH);if (ret != Z_STREAM_END) {fprintf(stderr, "压缩失败\n");deflateEnd(&strm);exit(EXIT_FAILURE);}// 获取压缩后的数据大小*output_size = strm.total_out;// 结束压缩deflateEnd(&strm);
}void decompress_data(const char *input_data, int input_size, char *output_data, int *output_size) {z_stream strm;int ret;// 初始化z_stream结构memset(&strm, 0, sizeof(strm));strm.zalloc = Z_NULL;strm.zfree = Z_NULL;strm.opaque = Z_NULL;// 设置解压缩ret = inflateInit(&strm);if (ret != Z_OK) {fprintf(stderr, "解压缩初始化失败\n");exit(EXIT_FAILURE);}// 设置输入数据strm.avail_in = input_size;strm.next_in = (Bytef *)input_data;// 设置输出数据strm.avail_out = *output_size;strm.next_out = (Bytef *)output_data;// 执行解压缩ret = inflate(&strm, Z_FINISH);if (ret != Z_STREAM_END) {fprintf(stderr, "解压缩失败\n");inflateEnd(&strm);exit(EXIT_FAILURE);}// 获取解压缩后的数据大小*output_size = strm.total_out;// 结束解压缩inflateEnd(&strm);
}int main() {char input_data[BUFFER_SIZE] = "This is some test data for compression and decompression. This is some test data for compression and decompression";char compressed_data[BUFFER_SIZE];char decompressed_data[BUFFER_SIZE];int compressed_size = BUFFER_SIZE;int decompressed_size = BUFFER_SIZE;// 压缩数据compress_data(input_data, strlen(input_data), compressed_data, &compressed_size);printf("压缩后大小: %d\n", compressed_size);// 解压数据decompress_data(compressed_data, compressed_size, decompressed_data, &decompressed_size);printf("解压后大小: %d\n", decompressed_size);printf("解压后数据: %s\n", decompressed_data);return 0;
}
2.4 交叉编译app程序
aarch64-linux-gnu-gcc gzip_demo.c -o zdemo -I /home/xhome/opt/opt_lib/include -L /home/xhome/opt/opt_lib/lib -lz
2.5 压缩及效率测试