中文 第三版
入門
閱讀由境,能看懂。但是代碼不敲一下拼卵。感覺缺點(diǎn)什么奢浑。
比如以第10頁的 出錯(cuò)處理
代碼為例。
#include "apue.h"
#include<errno.h>
#include<string.h>
int main(int argc, char *argv[]) {
fprintf(stderr, "EACCSS: %s\n", strerror(EACCES));
errno = ENOENT;
perror(argv[0]);
return 0;
}
apue.h 是書中代碼包里面的一個(gè)頭文件腋腮。你不下載雀彼。你可以#include<stdio.h>
。我是為了保持一致就down了一份即寡。照著源碼的目錄放了徊哑。自己練習(xí)保持一致。
../apue
├── include
│ └── apue.h
└── intro
├── Makefile
└── testerror.c
像我這對(duì)gcc參數(shù)都不大知曉的聪富。上來直接對(duì) testerror.c 莺丑。gcc testerror.c -o testerror
就報(bào)錯(cuò)了。
? intro gcc testerror.c -o testerror
testerror.c:1:10: fatal error: 'apue.h' file not found
#include "apue.h"
^~~~~~~~
1 error generated.
其實(shí)找不到頭文件墩蔓。那需要指定目錄梢莽。改成:
gcc testerror.c -I../include -o testerror
makefile 的編寫
每次都要敲這么長的命令。多麻煩奸披。
testerror:testerror.o
gcc testerror.o -o testerror
testerror.o:testerror.c
gcc testerror.c -I../include -c -Wall -g -o testerror.o
clean:
rm *.o testerror
精簡
OBJS=testerror.o
CC=gcc
CFLAGS+=-I../include -c -Wall -g
testerror:$(OBJS)
$(CC) $(OBJS) -o testerror
testerror.o:testerror.c
$(CC) testerror.c $(CFLAGS) -o testerror.o
clean:
$(RM) *.o testerror
再精簡
OBJS=testerror.o
CC=gcc
CFLAGS+= -I../include -c -Wall -g
testerror:$(OBJS)
$(CC) $^ -o $@
testerror.o:testerror.c
$(CC) $^ $(CFLAGS) -o $@
clean:
$(RM) *.o testerror
精簡
OBJS=testerror.o
CC=gcc
CFLAGS+=-I../include -c -Wall -g
testerror:$(OBJS)
$(CC) $^ -o $@
%.o:%.c
$(CC) $^ $(CFLAGS) -o $@
clean:
$(RM) *.o testerror
如果看不懂昏名。請(qǐng)看下參考資料。
再看下書中源碼包的intro目錄阵面。目錄下也有一個(gè)makefile文件轻局。人家的源碼文件可以生成多個(gè)洪鸭。然后參考這個(gè)makefile文件。我們改造下自己的仑扑。
ROOT=..
CC=gcc
CFLAGS+= -I$(ROOT)/include -c -Wall -g
PROGS = testerror
all: $(PROGS)
$(PROGS):%:%.o
$(CC) $^ -o $@
%.o:%.c
$(CC) $^ $(CFLAGS) -o $@
clean:
$(RM) $(PROGS) *.o
上面的Makefile文件览爵。都是先生成目標(biāo)文件.o文件。然后再鏈接夫壁。其實(shí)Makefile可以簡化成拾枣。
ROOT=..
CC=gcc
CFLAGS+= -I$(ROOT)/include
PROGS = testerror
all: $(PROGS)
%:%.c
$(CC) $^ $(CFLAGS) -o $@
clean:
$(RM) $(PROGS) *.o
如上沃疮,看起來跟apue源碼包intro目錄下的Makefile 有點(diǎn)相似了盒让。
ok,再練習(xí)另一個(gè)程序(1.8小節(jié):用戶標(biāo)識(shí))司蔬。
#include "apue.h"
int main(void)
{
printf("uid = %d, gid = %d\n", getuid(), getgid());
return 0;
}
我們只需要把uidgid 放到Makefile文件里面邑茄。
ROOT=..
CC=gcc
CFLAGS+= -I$(ROOT)/include
PROGS = testerror uidgid
all: $(PROGS)
%:%.c
$(CC) $^ $(CFLAGS) -o $@
clean:
$(RM) $(PROGS) *.o
make 一下就編譯出來了uidgid。
參考資料:
- 《如何編寫makefile》https://www.bilibili.com/video/av97776979/