Ubuntu编译APUE源码

78 阅读1分钟

说明

在写APUE书上相关代码的时候需要引入apue.h头文件,并且链接时候也需要apue的库,因此我们在Ubuntu上编译一下。

使用的Ubuntu版本

我们使用Ubuntu18.04进行编译

root@ubuntu:~# lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 18.04.6 LTS
Release:	18.04
Codename:	bionic

Ubuntu安装编译工具链

apt install build-essential libbsd-dev

下载APUE相关源码

wget http://www.apuebook.com/src.3e.tar.gz

开始编译

tar -xf src.3e.tar.gz
cd apue.3e/
make

编译完成后复制头文件和库文件到相应的系统目录中

cp /root/apue.3e/include/apue.h /usr/include/
cp /root/apue.3e/lib/libapue.a /usr/lib/

代码测试

创建mygetpid.c文件,文件内容如下

#include "apue.h"

int main(void)
{
  printf("Hello world from process ID %ld\n", (long)getpid());
  exit(0);
}

编译运行

gcc -o mygetpid mygetpid.c -lapue

# 运行
 ./mygetpid 
Hello world from process ID 4696

遇到的错误

错误一: 链接时候缺少bsd库

make[1]: Leaving directory '/root/apue.3e/threadctl'
making threads
make[1]: Entering directory '/root/apue.3e/threads'
gcc -ansi -I../include -Wall -DLINUX -D_GNU_SOURCE  badexit2.c -o badexit2  -L../lib -lapue -pthread -lrt -lbsd
/usr/bin/ld: cannot find -lbsd
collect2: error: ld returned 1 exit status
Makefile:31: recipe for target 'badexit2' failed
make[1]: *** [badexit2] Error 1
make[1]: Leaving directory '/root/apue.3e/threads'
Makefile:6: recipe for target 'all' failed

image.png

解决办法:安装相应的库

apt-get install libbsd-dev

参考文章