R PM 是 Red Hat 发起的一种包管理格式, 现在 Fedora, Open SUSE 都在使用 RPM 作为包管理工具。本文以一个例子介绍下如何从 source build 一个 RPM 包。
所需工具: rpmbuild
笔者使用的 rpmbuild 版本是:
[lgao@lgao ~]$ rpmbuild --version
RPM version 4.9.1.3
如果你没有该软件,请 Fedora 下使用以下命令安装:
[root@lgao ~]# yum install rpm-build
或者 Ubuntu 下使用:
[root@lgao ~]# apt-get install rpm-build
安装完 rpmbuild 后, 在自己用户主目录下创建以下结构:
[lgao@lgao ~]$ tree rpmbuild
rpmbuild
|-- BUILD
|-- BUILDROOT
|-- RPMS
| |-- i386
| `-- noarch
|-- SOURCES
|-- SPECS
|-- SRPMS
`-- tmp
其中:
- RPMS 目录保存了产生的 RPM 文件包, 根据 os arch 的不同, 可能存放在不同的子目录下。
- SOURCES 目录保存了 build RPM 之前的 source 文件, 一般会是压缩文件。
- SPECS 目录保存了 spec 文件, rpmbuild 就是根据这个 spec 文件进行的 build。
- SRPMS 目录保存了 source rpm 文件, srpm 用于特殊场合的 rebuild。
接下来我们以 helloworld 为例 build 一个 helloworld.rpm 出来。helloworld 的 source 在: https://github.com/gaol/helloworld
我们接下来运行:
[lgao@lgao SOURCES]$ git clone https://github.com/gaol/helloworld.git
Cloning into 'helloworld'...
remote: Counting objects: 9, done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 9 (delta 0), reused 6 (delta 0)
Unpacking objects: 100% (9/9), done.
[lgao@lgao SOURCES]$ cd helloworld/ && git archive --format=tar --prefix=helloworld-1.0.0/ 1.0.0 | xz > ../helloworld-1.0.0.tar.xz
以上命令是在 ~/rpmbuild/SOURCES 目录下将 helloworld version 为 1.0.0 的代码压缩为一个文件备用。
之后,我们在 ~/rpmbuild/SPECS 目录下创建 helloworld.spec 文件, 填充内容:
Name: helloworld
Version: 1.0.0
Release: 1%{?dist}
Summary: Hello World
Group: Development/Libraries
License: LGPLv2+
URL: https://github.com/gaol/helloworld.git
# git clone https://github.com/gaol/helloworld.git
# cd helloworld/ && git archive --format=tar --prefix=helloworld-1.0.0/ 1.0.0 | xz > ../helloworld-1.0.0.tar.xz
Source0: %{name}-%{version}.tar.xz
BuildArch: i386
BuildRequires: gcc
%description
The HelloWorld in C
%prep
%setup -q -n %{name}-%{version}
%build
gcc -o helloworld helloworld.c
%install
install -d -m 755 $RPM_BUILD_ROOT/usr/bin
install -m 755 helloworld $RPM_BUILD_ROOT/usr/bin/helloworld
%files
/usr/bin/helloworld
%changelog
* Mon Jun 25 2012 You Name <yName@ycomp.com> 1.0.0-1
- Initial packaging
大概解释下 spec 文件:
- Name 不用说, 是这个 pacakge 的名字, 与文件名相符。
- Version 用来 build 的 source code 版本。
- Release 发行号。同一个版本下的多次 build, 包括一些 patch在内的变化,记录在 Release 上。
- Group 在 Linux 软件中属于哪个组。
- License 软件的版权。 必须填写。
- URL 软件地址。
- Source0 第0个 source tarball。一般注释写出如何得出该 tarball 的。
- BuildArch 目标 OS Arch 是什么, 一般: i386, i686_64 等。
- BuildRequires 编译代码需要的软件, 此例中只需要 gcc。
- %prep 此 section 下一般把 source 从 tarball 解压出来, 如果有 patch 的话,也在此 section 下完成。
- %build 此 section 下完成 build 的工作
- %install 此 section 下把生成的文件放入 RPM 文件目录下
- %files 此 section 下列出 RPM 文件列表
- %changelog 列出更改记录。
创建了 spec 文件后, 运行:
rpmbuild -bb helloworld.spec
如果执行成功, helloworld 的 RPM 包就会出现在 ~/rpmbuild/RPMS/i386/ 目录下。
参考资料:
- Maximum RPM - http://www.rpm.org/max-rpm/
- RPM in Fedora - http://fedoraproject.org/wiki/How_to_create_an_RPM_package