中文 第三版
入門
閱讀,能看懂。但是代碼不敲一下。感覺缺點(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 的編寫
每次都要敲這么長(zhǎng)的命令。多麻煩。
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
精簡(jiǎn)
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
再精簡(jiǎn)
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
精簡(jiǎn)
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可以簡(jiǎn)化成。
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/