apue相关代码编译时链接问题

Problems linking during compile of apue related code

我正在尝试编译与本书相关的代码"Advanced Programming in the UNIX® Environment"

当我尝试像这样编译测试文件时:

$ gcc -L ../lib/ -l apue foo.c

我得到:

/tmp/cccXkUae.o: In function `main':
foo.c:(.text+0x2b): undefined reference to `err_sys'
...
collect2: error: ld returned 1 exit status

但是,函数似乎是在库中定义的...

$ grep err_sys ../lib/libapue.a 
Binary file ../lib/libapue.a matches

最终,编译没有错误:

$ gcc foo.c ../lib/error.c

只是想了解我做错了什么。

如果您 link 使用静态库(例如 linux 上的 *.a 文件),那么您可以像这样编译您的程序:

gcc foo.c ../lib/libapue.a

如果您想 link 使用动态(共享)库(例如 linux 上的 *.a 文件),则可以使用您建议的命令:

gcc -L../lib/ foo.c -lapue

源代码可用 在 http://www.apuebook.com/src.3e.tar.gz 处(在构建之后)在 include/ 中获取名为 apue.h 的 header 和在 lib 中名为 libapue.a 的静态库。因此,要针对 libapue 进行编译和 link,您需要:

gcc -I $apue_root/include -L $apue_root/lib your_file.c -lapue