《Beginning Linux Programming》读书笔记(四)

来源:互联网 发布:java 获取graphics 编辑:程序博客网 时间:2024/05/28 15:06

1, 读写空指针

先看第一种情况,printf试图访问空指针,以打印出字符串,而sprintf试图向空指针写入字符串,这时,linux会在GNU C函数库的帮助下,允许读空指针,但不允许写空指针。

#include <unistd.h>
#include 
<stdlib.h>
#include 
<stdio.h>

int main() 
{
    
char *some_memory = (char *)0;
    printf(
"A read from null %s/n", some_memory);
    sprintf(some_memory, 
"A write to null/n"); 
    exit(EXIT_SUCCESS);
}

再来看第2种情况,直接读地址0的数据,这时没有GNU libc函数库在我们和内核之间了,因此不允许执行。

#include <unistd.h>
#include 
<stdlib.h>
#include 
<stdio.h>

int main()
 {
    
char z = *(const char *)0;
    printf(
"I read from location zero/n");
    exit(EXIT_SUCCESS);
}

2,今天看到400页了,做个小结。第三章文件和目录,第四章参数,选项处理和环境变量,第五章和第六章都是终端的编程,第7章内存管理和文件加锁机制,包括整个文件封锁和部分区域封锁,第八章MySQL跳过不看,

3,使用make命令就可以完成编译,修改某些源码后再次make就可以编译修改部分与其他引用到的文件。下面是最简单的一个示例:

main.c

#include <stdio.h>
#include 
"hello.h"

int main()
{
    printf(
"hi,first line/n");
    sayHello();
    
return 0;
}

hello.h

void sayHello();

hello.c

#include "hello.h"

void sayHello()
{
    printf(
"hello,world/n");
}

Makefile

helloworld: main.o hello.o
    gcc 
-o helloworld main.o hello.o
main.o: main.c hello.h
    gcc 
-c main.c -o main.o
hello.o: hello.c hello.h
    gcc 
-c hello.c -o hello.o 
clean:
    rm 
-rf *.o helloworld

执行

make 
.
/helloworld
make clean

4,对上面Makefile的第一个改进版本

OBJFILE = main.o hello.o
CC 
= gcc
CFLAGS 
= -Wall --g
    
helloworld: $(OBJFILE)
    $(CC) 
-o helloworld $(OBJFILE)
main.o: main.c hello.h
    $(CC) $(CFLAGS) 
-c main.c -o main.o
hello.o: hello.c hello.h
    $(CC) $(CFLAGS) 
-c hello.c -o hello.o 
clean:
    rm 
-rf *.o helloworld

5,对上面Makefile的第二个改进版本

CC = gcc
CFLAGS 
= -Wall --g
TARGET 
= ./helloworld
    
%.o: %.c
    $(CC) $(CFLAGS) 
-c $< -o $@
SOURCES 
= $(wildcard *.c)
OBJFILE 
= $(patsubst %.c,%.o,$(SOURCES))
$(TARGET): $(OBJFILE)
    $(CC) $(OBJFILE) 
-o $(TARGET)
    chmod a
+x $(TARGET)
clean:
    rm 
-rf *.o $(TARGET)

6,上面Makefile的第三个改进版本,加入install功能

#which complier
CC 
= gcc
#
where to install
INSTDIR 
= /usr/local/bin
#
where are include files kept
INCLUDE 
= .
#options 
for dev
CFLAGS 
= -Wall --g

TARGET 
= ./helloworld
    
%.o: %.c
    $(CC) $(CFLAGS) 
-c $< -o $@
SOURCES 
= $(wildcard *.c)
OBJFILE 
= $(patsubst %.c,%.o,$(SOURCES))
$(TARGET): $(OBJFILE)
    $(CC) $(OBJFILE) 
-o $(TARGET)
    chmod a
+x $(TARGET)
clean:
    rm 
-rf *.o 
install: $(TARGET)
    @if [ 
-d $(INSTDIR) ]; /
    then /
        cp $(TARGET) $(INSTDIR);/
        chmod a
+x $(INSTDIR)/$(TARGET);/
        chmod og
-w $(INSTDIR)/$(TARGET);/
        echo 
"installed in $(INSTDIR)";/
    
else /
        echo 
"sorry,$(INSTDIR) does not exist";/
    fi

执行:

make install
make clean

 

参考资料:

1,《Linux平台Makefile文件的编写基础篇

原创粉丝点击