├── .gitignore ├── README.md ├── clang ├── How-to-Write-Makefile.md ├── README.md └── upload.go ├── golang ├── Pkg-bufio.md ├── Pkg-bytes.md ├── Pkg-expvar.go ├── Pkg-expvar.md ├── Pkg-ioutil.md ├── Pkg-list.md ├── Pkg-log.md ├── Pkg-sort.md ├── README.md └── upload.go ├── groovy └── groovy笔记.md ├── java ├── README.md ├── jps.jstat.remote.md ├── visualvm1.png └── visualvm2.png ├── myBatis ├── README.md ├── upload.go └── 一个简单的例子.md ├── scala.note.2.md ├── scala.note.md ├── scala.note.set.png ├── zookeeper ├── README.md ├── ZooKeeper Java API.md ├── ZooKeeper--数据模型.md ├── ZooKeeper示例 分布式锁.md ├── ZooKeeper示例 实时更新server列表.md ├── Zookeeper--安装和配置.md ├── get.png ├── ls.png ├── model.jpg └── upload.go └── 在hadoop中引入LZO.md /.gitignore: -------------------------------------------------------------------------------- 1 | _* 2 | */_* 3 | .* 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Blogs 2 | ---- 3 | My blog for Golang, Linux, Shell, C... 4 | Please see the subdir for detail. 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /clang/How-to-Write-Makefile.md: -------------------------------------------------------------------------------- 1 | How to Write Makefile 2 | ---- 3 | 4 | 转载自[陈皓的Blog](http://blog.csdn.net/haoel/article/details/2886) 5 | 6 | 什么是makefile?或许很多Winodws的程序员都不知道这个东西,因为那些Windows的IDE都为你做了这个工作,但我觉得要作一个好的和professional的程序员,makefile还是要懂。这就好像现在有这么多的HTML的编辑器,但如果你想成为一个专业人士,你还是要了解HTML的标识的含义。特别在Unix下的软件编译,你就不能不自己写makefile了,会不会写makefile,从一个侧面说明了一个人是否具备完成大型工程的能力。 7 | 8 | 因为,makefile关系到了整个工程的编译规则。一个工程中的源文件不计数,其按类型、功能、模块分别放在若干个目录中,makefile定义了一系列的规则来指定,哪些文件需要先编译,哪些文件需要后编译,哪些文件需要重新编译,甚至于进行更复杂的功能操作,因为makefile就像一个Shell脚本一样,其中也可以执行操作系统的命令。 9 | 10 | makefile带来的好处就是——"自动化编译",一旦写好,只需要一个make命令,整个工程完全自动编译,极大的提高了软件开发的效率。make是一个命令工具,是一个解释makefile中指令的命令工具,一般来说,大多数的IDE都有这个命令,比如:Delphi的make,Visual C++的nmake,Linux下GNU的make。可见,makefile都成为了一种在工程方面的编译方法。 11 | 12 | 现在讲述如何写makefile的文章比较少,这是我想写这篇文章的原因。当然,不同产商的make各不相同,也有不同的语法,但其本质都是在"文件依赖性"上做文章,这里,我仅对GNU的make进行讲述,我的环境是RedHat Linux 8.0,make的版本是3.80。必竟,这个make是应用最为广泛的,也是用得最多的。而且其还是最遵循于IEEE 1003.2-1992 标准的(POSIX.2)。 13 | 14 | 在这篇文档中,将以C/C++的源码作为我们基础,所以必然涉及一些关于C/C++的编译的知识,相关于这方面的内容,还请各位查看相关的编译器的文档。这里所默认的编译器是UNIX下的GCC和CC。 15 | 16 | 17 | ## 关于程序的编译和链接 18 | 19 | 在此,我想多说关于程序编译的一些规范和方法,一般来说,无论是C、C++、还是pas,首先要把源文件编译成中间代码文件,在Windows下也就是 .obj 文件,UNIX下是 .o 文件,即 Object File,这个动作叫做编译(compile)。然后再把大量的Object File合成执行文件,这个动作叫作链接(link)。 20 | 21 | 编译时,编译器需要的是语法的正确,函数与变量的声明的正确。对于后者,通常是你需要告诉编译器头文件的所在位置(头文件中应该只是声明,而定义应该放在C/C++文件中),只要所有的语法正确,编译器就可以编译出中间目标文件。一般来说,每个源文件都应该对应于一个中间目标文件(O文件或是OBJ文件)。 22 | 23 | 链接时,主要是链接函数和全局变量,所以,我们可以使用这些中间目标文件(O文件或是OBJ文件)来链接我们的应用程序。链接器并不管函数所在的源文件,只管函数的中间目标文件(Object File),在大多数时候,由于源文件太多,编译生成的中间目标文件太多,而在链接时需要明显地指出中间目标文件名,这对于编译很不方便,所以,我们要给中间目标文件打个包,在Windows下这种包叫"库文件"(Library File),也就是 .lib 文件,在UNIX下,是Archive File,也就是 .a 文件。 24 | 25 | 总结一下,源文件首先会生成中间目标文件,再由中间目标文件生成执行文件。在编译时,编译器只检测程序语法,和函数、变量是否被声明。如果函数未被声明,编译器会给出一个警告,但可以生成Object File。而在链接程序时,链接器会在所有的Object File中找寻函数的实现,如果找不到,那到就会报链接错误码(Linker Error),在VC下,这种错误一般是:Link 2001错误,意思说是说,链接器未能找到函数的实现。你需要指定函数的Object File. 26 | 27 | 好,言归正传,GNU的make有许多的内容,闲言少叙,还是让我们开始吧。 28 | 29 | 30 | ## Makefile 介绍 31 | 32 | make命令执行时,需要一个 Makefile 文件,以告诉make命令需要怎么样的去编译和链接程序。 33 | 34 | 首先,我们用一个示例来说明Makefile的书写规则。以便给大家一个感兴认识。这个示例来源于GNU的make使用手册,在这个示例中,我们的工程有8个C文件,和3个头文件,我们要写一个Makefile来告诉make命令如何编译和链接这几个文件。我们的规则是: 35 | 36 | + 如果这个工程没有编译过,那么我们的所有C文件都要编译并被链接。 37 | + 如果这个工程的某几个C文件被修改,那么我们只编译被修改的C文件,并链接目标程序。 38 | + 如果这个工程的头文件被改变了,那么我们需要编译引用了这几个头文件的C文件,并链接目标程序。 39 | 40 | 只要我们的Makefile写得够好,所有的这一切,我们只用一个make命令就可以完成,make命令会自动智能地根据当前的文件修改的情况来确定哪些文件需要重编译,从而自己编译所需要的文件和链接目标程序。 41 | 42 | 43 | ### Makefile的规则 44 | 45 | 在讲述这个Makefile之前,还是让我们先来粗略地看一看Makefile的规则。 46 | ```make 47 | target ...: prerequisites ... 48 | command 49 | ... 50 | ... 51 | ``` 52 | target也就是一个目标文件,可以是Object File,也可以是执行文件。还可以是一个标签(Label),对于标签这种特性,在后续的"伪目标"章节中会有叙述。prerequisites就是,要生成那个target所需要的文件或是目标。command也就是make需要执行的命令。(任意的Shell命令) 53 | 54 | 这是一个文件的依赖关系,也就是说,target这一个或多个的目标文件依赖于prerequisites中的文件,其生成规则定义在command中。说白一点就是说,prerequisites中如果有一个以上的文件比target文件要新的话,command所定义的命令就会被执行。这就是Makefile的规则。也就是Makefile中最核心的内容。 55 | 56 | 说到底,Makefile的东西就是这样一点,好像我的这篇文档也该结束了。呵呵。还不尽然,这是Makefile的主线和核心,但要写好一个Makefile还不够,我会以后面一点一点地结合我的工作经验给你慢慢到来。内容还多着呢。:) 57 | 58 | ### 一个示例 59 | 60 | 正如前面所说的,如果一个工程有3个头文件,和8个C文件,我们为了完成前面所述的那三个规则,我们的Makefile应该是下面的这个样子的。 61 | ```make 62 | edit: main.o kbd.o command.o display.o insert.o search.o files.o utils.o 63 | cc -o edit main.o kbd.o command.o display.o insert.o search.o files.o utils.o 64 | 65 | main.o: main.c defs.h 66 | cc -c main.c 67 | kbd.o: kbd.c defs.h command.h 68 | cc -c kbd.c 69 | command.o: command.c defs.h command.h 70 | cc -c command.c 71 | display.o: display.c defs.h buffer.h 72 | cc -c display.c 73 | insert.o: insert.c defs.h buffer.h 74 | cc -c insert.c 75 | search.o: search.c defs.h buffer.h 76 | cc -c search.c 77 | files.o: files.c defs.h buffer.h command.h 78 | cc -c files.c 79 | utils.o: utils.c defs.h 80 | cc -c utils.c 81 | clean : 82 | rm edit main.o kbd.o command.o display.o insert.o search.o files.o utils.o 83 | ``` 84 | 反斜杠(/)是换行符的意思。这样比较便于Makefile的易读。我们可以把这个内容保存在文件为"Makefile"或"makefile"的文件中,然后在该目录下直接输入命令"make"就可以生成执行文件edit。如果要删除执行文件和所有的中间目标文件,那么,只要简单地执行一下"make clean"就可以了。 85 | 86 | 在这个makefile中,目标文件(target)包含:执行文件edit和中间目标文件(*.o),依赖文件(prerequisites)就是冒号后面的那些 .c 文件和 .h文件。每一个 .o 文件都有一组依赖文件,而这些 .o 文件又是执行文件 edit 的依赖文件。依赖关系的实质上就是说明了目标文件是由哪些文件生成的,换言之,目标文件是哪些文件更新的。 87 | 88 | 在定义好依赖关系后,后续的那一行定义了如何生成目标文件的操作系统命令,一定要以一个Tab键作为开头。记住,make并不管命令是怎么工作的,他只管执行所定义的命令。make会比较targets文件和prerequisites文件的修改日期,如果prerequisites文件的日期要比targets文件的日期要新,或者target不存在的话,那么,make就会执行后续定义的命令。 89 | 90 | 这里要说明一点的是,clean不是一个文件,它只不过是一个动作名字,有点像C语言中的lable一样,其冒号后什么也没有,那么,make就不会自动去找文件的依赖性,也就不会自动执行其后所定义的命令。要执行其后的命令,就要在make命令后明显得指出这个lable的名字。这样的方法非常有用,我们可以在一个makefile中定义不用的编译或是和编译无关的命令,比如程序的打包,程序的备份,等等。 91 | 92 | ### make是如何工作的 93 | 94 | 在默认的方式下,也就是我们只输入make命令。那么, 95 | 96 | + make会在当前目录下找名字叫"Makefile"或"makefile"的文件。 97 | + 如果找到,它会找文件中的第一个目标文件(target),在上面的例子中,他会找到"edit"这个文件,并把这个文件作为最终的目标文件。 98 | + 如果edit文件不存在,或是edit所依赖的后面的 .o 文件的文件修改时间要比edit这个文件新,那么,他就会执行后面所定义的命令来生成edit这个文件。 99 | + 如果edit所依赖的.o文件也存在,那么make会在当前文件中找目标为.o文件的依赖性,如果找到则再根据那一个规则生成.o文件。(这有点像一个堆栈的过程) 100 | + 当然,你的C文件和H文件是存在的啦,于是make会生成 .o 文件,然后再用 .o 文件生命make的终极任务,也就是执行文件edit了。 101 | 102 | 这就是整个make的依赖性,make会一层又一层地去找文件的依赖关系,直到最终编译出第一个目标文件。在找寻的过程中,如果出现错误,比如最后被依赖的文件找不到,那么make就会直接退出,并报错,而对于所定义的命令的错误,或是编译不成功,make根本不理。make只管文件的依赖性,即,如果在我找了依赖关系之后,冒号后面的文件还是不在,那么对不起,我就不工作啦。 103 | 104 | 通过上述分析,我们知道,像clean这种,没有被第一个目标文件直接或间接关联,那么它后面所定义的命令将不会被自动执行,不过,我们可以显示要make执行。即命令——"make clean",以此来清除所有的目标文件,以便重编译。 105 | 106 | 于是在我们编程中,如果这个工程已被编译过了,当我们修改了其中一个源文件,比如file.c,那么根据我们的依赖性,我们的目标file.o会被重编译(也就是在这个依性关系后面所定义的命令),于是file.o的文件也是最新的啦,于是file.o的文件修改时间要比edit要新,所以edit也会被重新链接了(详见edit目标文件后定义的命令)。 107 | 108 | 而如果我们改变了"command.h",那么,kdb.o、command.o和files.o都会被重编译,并且,edit会被重链接。 109 | 110 | ### makefile中使用变量 111 | 112 | 在上面的例子中,先让我们看看edit的规则: 113 | ```make 114 | edit: main.o kbd.o command.o display.o insert.o search.o files.o utils.o 115 | cc -o edit main.o kbd.o command.o display.o insert.o search.o files.o utils.o 116 | ``` 117 | 我们可以看到[.o]文件的字符串被重复了两次,如果我们的工程需要加入一个新的[.o]文件,那么我们需要在两个地方加(应该是三个地方,还有一个地方在clean中)。当然,我们的makefile并不复杂,所以在两个地方加也不累,但如果makefile变得复杂,那么我们就有可能会忘掉一个需要加入的地方,而导致编译失败。所以,为了makefile的易维护,在makefile中我们可以使用变量。makefile的变量也就是一个字符串,理解成C语言中的宏可能会更好。 118 | 119 | 比如,我们声明一个变量,叫objects, OBJECTS, objs, OBJS, obj, 或是 OBJ,反正不管什么啦,只要能够表示obj文件就行了。我们在makefile一开始就这样定义: 120 | `objects = main.o kbd.o command.o display.o insert.o search.o files.o utils.o` 121 | 122 | 于是,我们就可以很方便地在我们的makefile中以"$(objects)"的方式来使用这个变量了,于是我们的改良版makefile就变成下面这个样子: 123 | ```make 124 | objects = main.o kbd.o command.o display.o insert.o search.o files.o utils.o 125 | edit: $(objects) 126 | cc -o edit $(objects) 127 | main.o: main.c defs.h 128 | cc -c main.c 129 | kbd.o: kbd.c defs.h command.h 130 | cc -c kbd.c 131 | command.o: command.c defs.h command.h 132 | cc -c command.c 133 | display.o: display.c defs.h buffer.h 134 | cc -c display.c 135 | insert.o: insert.c defs.h buffer.h 136 | cc -c insert.c 137 | search.o: search.c defs.h buffer.h 138 | cc -c search.c 139 | files.o: files.c defs.h buffer.h command.h 140 | cc -c files.c 141 | utils.o: utils.c defs.h 142 | cc -c utils.c 143 | clean : 144 | rm edit $(objects) 145 | ``` 146 | 于是如果有新的 .o 文件加入,我们只需简单地修改一下 objects 变量就可以了。 147 | 关于变量更多的话题,我会在后续给你一一道来。 148 | 149 | ### 让make自动推导 150 | 151 | GNU的make很强大,它可以自动推导文件以及文件依赖关系后面的命令,于是我们就没必要去在每一个[.o]文件后都写上类似的命令,因为,我们的make会自动识别,并自己推导命令。 152 | 153 | 只要make看到一个[.o]文件,它就会自动的把[.c]文件加在依赖关系中,如果make找到一个whatever.o,那么whatever.c,就会是whatever.o的依赖文件。并且 cc -c whatever.c 也会被推导出来,于是,我们的makefile再也不用写得这么复杂。我们的是新的makefile又出炉了。 154 | ```make 155 | objects = main.o kbd.o command.o display.o insert.o search.o files.o utils.o 156 | edit: $(objects) 157 | cc -o edit $(objects) 158 | main.o: defs.h 159 | kbd.o: defs.h command.h 160 | command.o: defs.h command.h 161 | display.o: defs.h buffer.h 162 | insert.o: defs.h buffer.h 163 | search.o: defs.h buffer.h 164 | files.o: defs.h buffer.h command.h 165 | utils.o: defs.h 166 | 167 | .PHONY: clean 168 | clean : 169 | rm edit $(objects) 170 | ``` 171 | 这种方法,也就是make的"隐晦规则"。上面文件内容中,".PHONY"表示,clean是个伪目标文件。 172 | 173 | 关于更为详细的"隐晦规则"和"伪目标文件",我会在后续给你一一道来。 174 | 175 | ### 另类风格的makefile 176 | 177 | 即然我们的make可以自动推导命令,那么我看到那堆[.o]和[.h]的依赖就有点不爽,那么多的重复的[.h],能不能把其收拢起来,好吧,没有问题,这个对于make来说很容易,谁叫它提供了自动推导命令和文件的功能呢?来看看最新风格的makefile吧。 178 | ```make 179 | objects = main.o kbd.o command.o display.o insert.o search.o files.o utils.o 180 | 181 | edit: $(objects) 182 | cc -o edit $(objects) 183 | 184 | $(objects): defs.h 185 | kbd.o command.o files.o: command.h 186 | display.o insert.o search.o files.o: buffer.h 187 | 188 | .PHONY: clean 189 | clean : 190 | rm edit $(objects) 191 | ``` 192 | 这种风格,让我们的makefile变得很简单,但我们的文件依赖关系就显得有点凌乱了。鱼和熊掌不可兼得。还看你的喜好了。我是不喜欢这种风格的,一是文件的依赖关系看不清楚,二是如果文件一多,要加入几个新的.o文件,那就理不清楚了。 193 | 194 | ### 清空目标文件的规则 195 | 196 | 每个Makefile中都应该写一个清空目标文件(.o和执行文件)的规则,这不仅便于重编译,也很利于保持文件的清洁。这是一个"修养"(呵呵,还记得我的《编程修养》吗)。一般的风格都是: 197 | ```make 198 | clean: 199 | rm edit $(objects) 200 | ``` 201 | 更为稳健的做法是: 202 | ```make 203 | .PHONY: clean 204 | clean : 205 | -rm edit $(objects) 206 | ``` 207 | 前面说过,.PHONY意思表示clean是一个"伪目标",。而在rm命令前面加了一个小减号的意思就是,也许某些文件出现问题,但不要管,继续做后面的事。当然,clean的规则不要放在文件的开头,不然,这就会变成make的默认目标,相信谁也不愿意这样。不成文的规矩是——"clean从来都是放在文件的最后"。 208 | 209 | 上面就是一个makefile的概貌,也是makefile的基础,下面还有很多makefile的相关细节,准备好了吗?准备好了就来。 210 | 211 | 212 | ## Makefile 总述 213 | 214 | ### Makefile里有什么? 215 | 216 | Makefile里主要包含了五个东西:显式规则、隐晦规则、变量定义、文件指示和注释。 217 | 218 | + 显式规则。显式规则说明了,如何生成一个或多的的目标文件。这是由Makefile的书写者明显指出,要生成的文件,文件的依赖文件,生成的命令。 219 | + 隐晦规则。由于我们的make有自动推导的功能,所以隐晦的规则可以让我们比较粗糙地简略地书写Makefile,这是由make所支持的。 220 | + 变量的定义。在Makefile中我们要定义一系列的变量,变量一般都是字符串,这个有点你C语言中的宏,当Makefile被执行时,其中的变量都会被扩展到相应的引用位置上。 221 | + 文件指示。其包括了三个部分,一个是在一个Makefile中引用另一个Makefile,就像C语言中的include一样;另一个是指根据某些情况指定Makefile中的有效部分,就像C语言中的预编译#if一样;还有就是定义一个多行的命令。有关这一部分的内容,我会在后续的部分中讲述。 222 | + 注释。Makefile中只有行注释,和UNIX的Shell脚本一样,其注释是用"#"字符,这个就像C/C++中的"//"一样。如果你要在你的Makefile中使用"#"字符,可以用反斜框进行转义,如:"/#"。 223 | 224 | 最后,还值得一提的是,在Makefile中的命令,必须要以[Tab]键开始。 225 | 226 | ### Makefile的文件名 227 | 228 | 默认的情况下,make命令会在当前目录下按顺序找寻文件名为"GNUmakefile"、"makefile"、"Makefile"的文件,找到了解释这个文件。在这三个文件名中,最好使用"Makefile"这个文件名,因为,这个文件名第一个字符为大写,这样有一种显目的感觉。最好不要用"GNUmakefile",这个文件是GNU的make识别的。有另外一些make只对全小写的"makefile"文件名敏感,但是基本上来说,大多数的make都支持"makefile"和"Makefile"这两种默认文件名。 229 | 230 | 当然,你可以使用别的文件名来书写Makefile,比如:"Make.Linux","Make.Solaris","Make.AIX"等,如果要指定特定的Makefile,你可以使用make的"-f"和"--file"参数,如:make -f Make.Linux或make --file Make.AIX。 231 | 232 | ### 引用其它的Makefile 233 | 234 | 在Makefile使用include关键字可以把别的Makefile包含进来,这很像C语言的#include,被包含的文件会原模原样的放在当前文件的包含位置。include的语法是: 235 | `include [filename]` 236 | filename可以是当前操作系统Shell的文件模式(可以保含路径和通配符) 237 | 238 | 在include前面可以有一些空字符,但是绝不能是[Tab]键开始。include和[filename]可以用一个或多个空格隔开。举个例子,你有这样几个Makefile:a.mk、b.mk、c.mk,还有一个文件叫foo.make,以及一个变量$(bar),其包含了e.mk和f.mk,那么,下面的语句: 239 | `include foo.make *.mk $(bar)` 240 | 等价于: 241 | `include foo.make a.mk b.mk c.mk e.mk f.mk` 242 | 243 | make命令开始时,会把找寻include所指出的其它Makefile,并把其内容安置在当前的位置。就好像C/C++的#include指令一样。如果文件都没有指定绝对路径或是相对路径的话,make会在当前目录下首先寻找,如果当前目录下没有找到,那么,make还会在下面的几个目录下找: 244 | + 如果make执行时,有"-I"或"--include-dir"参数,那么make就会在这个参数所指定的目录下去寻找。 245 | + 如果目录[prefix]/include(一般是:/usr/local/bin或/usr/include)存在的话,make也会去找。 246 | 247 | 如果有文件没有找到的话,make会生成一条警告信息,但不会马上出现致命错误。它会继续载入其它的文件,一旦完成makefile的读取,make会再重试这些没有找到,或是不能读取的文件,如果还是不行,make才会出现一条致命信息。如果你想让make不理那些无法读取的文件,而继续执行,你可以在include前加一个减号"-"。如: 248 | `-include [filename]` 249 | 其表示,无论include过程中出现什么错误,都不要报错继续执行。和其它版本make兼容的相关命令是sinclude,其作用和这一个是一样的。 250 | 251 | ### 环境变量 MAKEFILES 252 | 253 | 如果你的当前环境中定义了环境变量MAKEFILES,那么,make会把这个变量中的值做一个类似于include的动作。这个变量中的值是其它的Makefile,用空格分隔。只是,它和include不同的是,从这个环境变中引入的Makefile的"目标"不会起作用,如果环境变量中定义的文件发现错误,make也会不理。 254 | 255 | 但是在这里我还是建议不要使用这个环境变量,因为只要这个变量一被定义,那么当你使用make时,所有的Makefile都会受到它的影响,这绝不是你想看到的。在这里提这个事,只是为了告诉大家,也许有时候你的Makefile出现了怪事,那么你可以看看当前环境中有没有定义这个变量。 256 | 257 | ### make的工作方式 258 | 259 | GNU的make工作时的执行步骤入下:(想来其它的make也是类似) 260 | 261 | + 读入所有的Makefile。 262 | + 读入被include的其它Makefile。 263 | + 初始化文件中的变量。 264 | + 推导隐晦规则,并分析所有规则。 265 | + 为所有的目标文件创建依赖关系链。 266 | + 根据依赖关系,决定哪些目标要重新生成。 267 | + 执行生成命令。 268 | 269 | 1-5步为第一个阶段,6-7为第二个阶段。第一个阶段中,如果定义的变量被使用了,那么,make会把其展开在使用的位置。但make并不会完全马上展开,make使用的是拖延战术,如果变量出现在依赖关系的规则中,那么仅当这条依赖被决定要使用了,变量才会在其内部展开。 270 | 271 | 当然,这个工作方式你不一定要清楚,但是知道这个方式你也会对make更为熟悉。有了这个基础,后续部分也就容易看懂了。 272 | 273 | 274 | ## 书写规则 275 | 276 | 规则包含两个部分,一个是依赖关系,一个是生成目标的方法。 277 | 278 | 在Makefile中,规则的顺序是很重要的,因为,Makefile中只应该有一个最终目标,其它的目标都是被这个目标所连带出来的,所以一定要让make知道你的最终目标是什么。一般来说,定义在Makefile中的目标可能会有很多,但是第一条规则中的目标将被确立为最终的目标。如果第一条规则中的目标有很多个,那么,第一个目标会成为最终的目标。make所完成的也就是这个目标。 279 | 280 | 好了,还是让我们来看一看如何书写规则。 281 | 282 | ### 规则举例 283 | ```make 284 | foo.o: foo.c defs.h # foo模块 285 | cc -c -g foo.c 286 | ``` 287 | 看到这个例子,各位应该不是很陌生了,前面也已说过,foo.o是我们的目标,foo.c和defs.h是目标所依赖的源文件,而只有一个命令"cc -c -g foo.c"(以Tab键开头)。这个规则告诉我们两件事: 288 | + 文件的依赖关系,foo.o依赖于foo.c和defs.h的文件,如果foo.c和defs.h的文件日期要比foo.o文件日期要新,或是foo.o不存在,那么依赖关系发生。 289 | + 如果生成(或更新)foo.o文件。也就是那个cc命令,其说明了,如何生成foo.o这个文件。(当然foo.c文件include了defs.h文件) 290 | 291 | ### 规则的语法 292 | ```make 293 | targets: prerequisites 294 | command 295 | ... 296 | ``` 297 | 或是这样: 298 | ```make 299 | targets: prerequisites ; command 300 | command 301 | ... 302 | ``` 303 | targets是文件名,以空格分开,可以使用通配符。一般来说,我们的目标基本上是一个文件,但也有可能是多个文件。 304 | 305 | command是命令行,如果其不与"target:prerequisites"在一行,那么,必须以[Tab键]开头,如果和prerequisites在一行,那么可以用分号做为分隔。(见上) 306 | 307 | prerequisites也就是目标所依赖的文件(或依赖目标)。如果其中的某个文件要比目标文件要新,那么,目标就被认为是"过时的",被认为是需要重生成的。这个在前面已经讲过了。 308 | 309 | 如果命令太长,你可以使用反斜框(‘/’)作为换行符。make对一行上有多少个字符没有限制。规则告诉make两件事,文件的依赖关系和如何成成目标文件。 310 | 311 | 一般来说,make会以UNIX的标准Shell,也就是/bin/sh来执行命令。 312 | 313 | ### 在规则中使用通配符 314 | 315 | 如果我们想定义一系列比较类似的文件,我们很自然地就想起使用通配符。make支持三各通配符:"*","?"和"[...]"。这是和Unix的B-Shell是相同的。 316 | 317 | 波浪号("~")字符在文件名中也有比较特殊的用途。如果是"~/test",这就表示当前用户的$HOME目录下的test目录。而"~hchen/test"则表示用户hchen的宿主目录下的test目录。(这些都是Unix下的小知识了,make也支持)而在Windows或是MS-DOS下,用户没有宿主目录,那么波浪号所指的目录则根据环境变量"HOME"而定。 318 | 319 | 通配符代替了你一系列的文件,如"*.c"表示所以后缀为c的文件。一个需要我们注意的是,如果我们的文件名中有通配符,如:"*",那么可以用转义字符"/",如"/*"来表示真实的"*"字符,而不是任意长度的字符串。 320 | 321 | 好吧,还是先来看几个例子吧: 322 | ```make 323 | clean: 324 | rm -f *.o 325 | ``` 326 | 上面这个例子我不不多说了,这是操作系统Shell所支持的通配符。这是在命令中的通配符。 327 | ```make 328 | print: *.c 329 | lpr -p $? 330 | touch print 331 | ``` 332 | 上面这个例子说明了通配符也可以在我们的规则中,目标print依赖于所有的[.c]文件。其中的"$?"是一个自动化变量,我会在后面给你讲述。 333 | ```make 334 | objects = *.o 335 | ``` 336 | 上面这个例子,表示了,通符同样可以用在变量中。并不是说[*.o]会展开,不!objects的值就是"*.o"。Makefile中的变量其实就是C/C++中的宏。如果你要让通配符在变量中展开,也就是让objects的值是所有[.o]的文件名的集合,那么,你可以这样: 337 | ```make 338 | objects := $(wildcard *.o) 339 | ``` 340 | 这种用法由关键字"wildcard"指出,关于Makefile的关键字,我们将在后面讨论。 341 | 342 | ### 文件搜寻 343 | 344 | 在一些大的工程中,有大量的源文件,我们通常的做法是把这许多的源文件分类,并存放在不同的目录中。所以,当make需要去找寻文件的依赖关系时,你可以在文件前加上路径,但最好的方法是把一个路径告诉make,让make在自动去找。 345 | 346 | Makefile文件中的特殊变量"VPATH"就是完成这个功能的,如果没有指明这个变量,make只会在当前的目录中去找寻依赖文件和目标文件。如果定义了这个变量,那么,make就会在当当前目录找不到的情况下,到所指定的目录中去找寻文件了。 347 | ```make 348 | VPATH = src:../headers 349 | ``` 350 | 上面的的定义指定两个目录,"src"和"../headers",make会按照这个顺序进行搜索。目录由"冒号"分隔。(当然,当前目录永远是最高优先搜索的地方) 351 | 352 | 另一个设置文件搜索路径的方法是使用make的"vpath"关键字(注意,它是全小写的),这不是变量,这是一个make的关键字,这和上面提到的那个VPATH变量很类似,但是它更为灵活。它可以指定不同的文件在不同的搜索目录中。这是一个很灵活的功能。它的使用方法有三种: 353 | 354 | + vpath [pattern] [directories] 355 | 为符合模式[pattern]的文件指定搜索目录[directories]。 356 | + vpath [pattern] 357 | 清除符合模式[pattern]的文件的搜索目录。 358 | + vpath 359 | 清除所有已被设置好了的文件搜索目录。 360 | 361 | vapth使用方法中的[pattern]需要包含"%"字符。"%"的意思是匹配零或若干字符,例如,"%.h"表示所有以".h"结尾的文件。[pattern]指定了要搜索的文件集,而[directories]则指定了[pattern]的文件集的搜索的目录。例如: 362 | ```make 363 | vpath %.h ../headers 364 | ``` 365 | 该语句表示,要求make在"../headers"目录下搜索所有以".h"结尾的文件。(如果某文件在当前目录没有找到的话) 366 | 367 | 我们可以连续地使用vpath语句,以指定不同搜索策略。如果连续的vpath语句中出现了相同的[pattern],或是被重复了的[pattern],那么,make会按照vpath语句的先后顺序来执行搜索。如: 368 | ```make 369 | vpath %.c foo 370 | vpath % blish 371 | vpath %.c bar 372 | ``` 373 | 其表示".c"结尾的文件,先在"foo"目录,然后是"blish",最后是"bar"目录。 374 | ```make 375 | vpath %.c foo:bar 376 | vpath % blish 377 | ``` 378 | 而上面的语句则表示".c"结尾的文件,先在"foo"目录,然后是"bar"目录,最后才是"blish"目录。 379 | 380 | ### 伪目标 381 | 382 | 最早先的一个例子中,我们提到过一个"clean"的目标,这是一个"伪目标", 383 | ```make 384 | clean: 385 | rm *.o temp 386 | ``` 387 | 正像我们前面例子中的"clean"一样,即然我们生成了许多文件编译文件,我们也应该提供一个清除它们的"目标"以备完整地重编译而用。 (以"make clean"来使用该目标) 388 | 389 | 因为,我们并不生成"clean"这个文件。"伪目标"并不是一个文件,只是一个标签,由于"伪目标"不是文件,所以make无法生成它的依赖关系和决定它是否要执行。我们只有通过显示地指明这个"目标"才能让其生效。当然,"伪目标"的取名不能和文件名重名,不然其就失去了"伪目标"的意义了。 390 | 391 | 当然,为了避免和文件重名的这种情况,我们可以使用一个特殊的标记".PHONY"来显示地指明一个目标是"伪目标",向make说明,不管是否有这个文件,这个目标就是"伪目标"。 392 | ```make 393 | .PHONY: clean 394 | ``` 395 | 只要有这个声明,不管是否有"clean"文件,要运行"clean"这个目标,只有"make clean"这样。于是整个过程可以这样写: 396 | ```make 397 | .PHONY: clean 398 | clean: 399 | rm *.o temp 400 | ``` 401 | 伪目标一般没有依赖的文件。但是,我们也可以为伪目标指定所依赖的文件。伪目标同样可以作为"默认目标",只要将其放在第一个。一个示例就是,如果你的Makefile需要一口气生成若干个可执行文件,但你只想简单地敲一个make完事,并且,所有的目标文件都写在一个Makefile中,那么你可以使用"伪目标"这个特性: 402 | ```make 403 | all: prog1 prog2 prog3 404 | .PHONY: all 405 | 406 | prog1: prog1.o utils.o 407 | cc -o prog1 prog1.o utils.o 408 | 409 | prog2: prog2.o 410 | cc -o prog2 prog2.o 411 | 412 | prog3: prog3.o sort.o utils.o 413 | cc -o prog3 prog3.o sort.o utils.o 414 | ``` 415 | 我们知道,Makefile中的第一个目标会被作为其默认目标。我们声明了一个"all"的伪目标,其依赖于其它三个目标。由于伪目标的特性是,总是被执行的,所以其依赖的那三个目标就总是不如"all"这个目标新。所以,其它三个目标的规则总是会被决议。也就达到了我们一口气生成多个目标的目的。".PHONY: all"声明了"all"这个目标为"伪目标"。 416 | 417 | 随便提一句,从上面的例子我们可以看出,目标也可以成为依赖。所以,伪目标同样也可成为依赖。看下面的例子: 418 | ```make 419 | .PHONY: cleanall cleanobj cleandiff 420 | 421 | cleanall: cleanobj cleandiff 422 | rm program 423 | 424 | cleanobj : 425 | rm *.o 426 | 427 | cleandiff : 428 | rm *.diff 429 | ``` 430 | "make clean"将清除所有要被清除的文件。"cleanobj"和"cleandiff"这两个伪目标有点像"子程序"的意思。我们可以输入"make cleanall"和"make cleanobj"和"make cleandiff"命令来达到清除不同种类文件的目的。 431 | 432 | ### 多目标 433 | 434 | Makefile的规则中的目标可以不止一个,其支持多目标,有可能我们的多个目标同时依赖于一个文件,并且其生成的命令大体类似。于是我们就能把其合并起来。当然,多个目标的生成规则的执行命令是同一个,这可能会可我们带来麻烦,不过好在我们的可以使用一个自动化变量"$@"(关于自动化变量,将在后面讲述),这个变量表示着目前规则中所有的目标的集合,这样说可能很抽象,还是看一个例子吧。 435 | ```make 436 | bigoutput littleoutput: text.g 437 | generate text.g -$(subst output,,$@) ] $@ 438 | ``` 439 | 上述规则等价于: 440 | ```make 441 | bigoutput: text.g 442 | generate text.g -big ] bigoutput 443 | littleoutput: text.g 444 | generate text.g -little ] littleoutput 445 | ``` 446 | 其中,-$(subst output,,$@)中的"$"表示执行一个Makefile的函数,函数名为subst,后面的为参数。关于函数,将在后面讲述。这里的这个函数是截取字符串的意思,"$@"表示目标的集合,就像一个数组,"$@"依次取出目标,并执于命令。 447 | 448 | ### 静态模式 449 | 450 | 静态模式可以更加容易地定义多目标的规则,可以让我们的规则变得更加的有弹性和灵活。我们还是先来看一下语法: 451 | ```make 452 | [targets ...]: [target-pattern]: [prereq-patterns ...] 453 | [commands] 454 | ... 455 | ``` 456 | targets定义了一系列的目标文件,可以有通配符。是目标的一个集合。 457 | target-parrtern是指明了targets的模式,也就是的目标集模式。 458 | prereq-parrterns是目标的依赖模式,它对target-parrtern形成的模式再进行一次依赖目标的定义。 459 | 460 | 这样描述这三个东西,可能还是没有说清楚,还是举个例子来说明一下吧。如果我们的[target-parrtern]定义成"%.o",意思是我们的[target]集合中都是以".o"结尾的,而如果我们的[prereq-parrterns]定义成"%.c",意思是对[target-parrtern]所形成的目标集进行二次定义,其计算方法是,取[target-parrtern]模式中的"%"(也就是去掉了[.o]这个结尾),并为其加上[.c]这个结尾,形成的新集合。 461 | 462 | 所以,我们的"目标模式"或是"依赖模式"中都应该有"%"这个字符,如果你的文件名中有"%"那么你可以使用反斜杠"/"进行转义,来标明真实的"%"字符。 463 | 464 | 看一个例子: 465 | ```make 466 | objects = foo.o bar.o 467 | 468 | all: $(objects) 469 | 470 | $(objects): %.o: %.c 471 | $(CC) -c $(CFLAGS) $[ -o $@ 472 | ``` 473 | 上面的例子中,指明了我们的目标从$object中获取,"%.o"表明要所有以".o"结尾的目标,也就是"foo.o bar.o",也就是变量$object集合的模式,而依赖模式"%.c"则取模式"%.o"的"%",也就是"foo bar",并为其加下".c"的后缀,于是,我们的依赖目标就是"foo.c bar.c"。而命令中的"$["和"$@"则是自动化变量,"$["表示所有的依赖目标集(也就是"foo.c bar.c"),"$@"表示目标集(也就是"foo.o bar.o")。于是,上面的规则展开后等价于下面的规则: 474 | ```make 475 | foo.o: foo.c 476 | $(CC) -c $(CFLAGS) foo.c -o foo.o 477 | bar.o: bar.c 478 | $(CC) -c $(CFLAGS) bar.c -o bar.o 479 | ``` 480 | 试想,如果我们的"%.o"有几百个,那种我们只要用这种很简单的"静态模式规则"就可以写完一堆规则,实在是太有效率了。"静态模式规则"的用法很灵活,如果用得好,那会一个很强大的功能。再看一个例子: 481 | ```make 482 | files = foo.elc bar.o lose.o 483 | 484 | $(filter %.o,$(files)): %.o: %.c 485 | $(CC) -c $(CFLAGS) $[ -o $@ 486 | $(filter %.elc,$(files)): %.elc: %.el 487 | emacs -f batch-byte-compile $[ 488 | ``` 489 | $(filter %.o,$(files))表示调用Makefile的filter函数,过滤"$filter"集,只要其中模式为"%.o"的内容。其的它内容,我就不用多说了吧。这个例字展示了Makefile中更大的弹性。 490 | 491 | ### 自动生成依赖性 492 | 493 | 在Makefile中,我们的依赖关系可能会需要包含一系列的头文件,比如,如果我们的main.c中有一句"#include "defs.h"",那么我们的依赖关系应该是: 494 | ```make 495 | main.o: main.c defs.h 496 | ``` 497 | 但是,如果是一个比较大型的工程,你必需清楚哪些C文件包含了哪些头文件,并且,你在加入或删除头文件时,也需要小心地修改Makefile,这是一个很没有维护性的工作。为了避免这种繁重而又容易出错的事情,我们可以使用C/C++编译的一个功能。大多数的C/C++编译器都支持一个"-M"的选项,即自动找寻源文件中包含的头文件,并生成一个依赖关系。例如,如果我们执行下面的命令: 498 | ```make 499 | cc -M main.c 500 | ``` 501 | 其输出是: 502 | ```make 503 | main.o: main.c defs.h 504 | ``` 505 | 于是由编译器自动生成的依赖关系,这样一来,你就不必再手动书写若干文件的依赖关系,而由编译器自动生成了。需要提醒一句的是,如果你使用GNU的C/C++编译器,你得用"-MM"参数,不然,"-M"参数会把一些标准库的头文件也包含进来。 506 | 507 | gcc -M main.c的输出是: 508 | ```make 509 | main.o: main.c defs.h /usr/include/stdio.h /usr/include/features.h / 510 | /usr/include/sys/cdefs.h /usr/include/gnu/stubs.h / 511 | /usr/lib/gcc-lib/i486-suse-linux/2.95.3/include/stddef.h / 512 | /usr/include/bits/types.h /usr/include/bits/pthreadtypes.h / 513 | /usr/include/bits/sched.h /usr/include/libio.h / 514 | /usr/include/_G_config.h /usr/include/wchar.h / 515 | /usr/include/bits/wchar.h /usr/include/gconv.h / 516 | /usr/lib/gcc-lib/i486-suse-linux/2.95.3/include/stdarg.h / 517 | /usr/include/bits/stdio_lim.h 518 | ``` 519 | gcc -MM main.c的输出则是: 520 | ```make 521 | main.o: main.c defs.h 522 | ``` 523 | 那么,编译器的这个功能如何与我们的Makefile联系在一起呢。因为这样一来,我们的Makefile也要根据这些源文件重新生成,让Makefile自已依赖于源文件?这个功能并不现实,不过我们可以有其它手段来迂回地实现这一功能。GNU组织建议把编译器为每一个源文件的自动生成的依赖关系放到一个文件中,为每一个"name.c"的文件都生成一个"name.d"的Makefile文件,[.d]文件中就存放对应[.c]文件的依赖关系。 524 | 525 | 于是,我们可以写出[.c]文件和[.d]文件的依赖关系,并让make自动更新或自成[.d]文件,并把其包含在我们的主Makefile中,这样,我们就可以自动化地生成每个文件的依赖关系了。 526 | 527 | 这里,我们给出了一个模式规则来产生[.d]文件: 528 | ```make 529 | %.d: %.c 530 | @set -e; rm -f $@; / 531 | $(CC) -M $(CPPFLAGS) $[ ] $@.$$$$; / 532 | sed 's,/($*/)/.o[ :]*,/1.o $@: ,g' [ $@.$$$$ ] $@; / 533 | rm -f $@.$$$$ 534 | ``` 535 | 这个规则的意思是,所有的[.d]文件依赖于[.c]文件,"rm -f $@"的意思是删除所有的目标,也就是[.d]文件,第二行的意思是,为每个依赖文件"$[",也就是[.c]文件生成依赖文件,"$@"表示模式"%.d"文件,如果有一个C文件是name.c,那么"%"就是"name","$$$$"意为一个随机编号,第二行生成的文件有可能是"name.d.12345",第三行使用sed命令做了一个替换,关于sed命令的用法请参看相关的使用文档。第四行就是删除临时文件。 536 | 537 | 总而言之,这个模式要做的事就是在编译器生成的依赖关系中加入[.d]文件的依赖,即把依赖关系: 538 | ```make 539 | main.o: main.c defs.h 540 | ``` 541 | 转成: 542 | ```make 543 | main.o main.d: main.c defs.h 544 | ``` 545 | 于是,我们的[.d]文件也会自动更新了,并会自动生成了,当然,你还可以在这个[.d]文件中加入的不只是依赖关系,包括生成的命令也可一并加入,让每个[.d]文件都包含一个完赖的规则。一旦我们完成这个工作,接下来,我们就要把这些自动生成的规则放进我们的主Makefile中。我们可以使用Makefile的"include"命令,来引入别的Makefile文件(前面讲过),例如: 546 | ```make 547 | sources = foo.c bar.c 548 | include $(sources:.c=.d) 549 | ``` 550 | 上述语句中的"$(sources:.c=.d)"中的".c=.d"的意思是做一个替换,把变量$(sources)所有[.c]的字串都替换成[.d],关于这个"替换"的内容,在后面我会有更为详细的讲述。当然,你得注意次序,因为include是按次来载入文件,最先载入的[.d]文件中的目标会成为默认目标。 551 | 552 | 553 | ## 书写命令 554 | 555 | 每条规则中的命令和操作系统Shell的命令行是一致的。make会一按顺序一条一条的执行命令,每条命令的开头必须以[Tab]键开头,除非,命令是紧跟在依赖规则后面的分号后的。在命令行之间中的空格或是空行会被忽略,但是如果该空格或空行是以Tab键开头的,那么make会认为其是一个空命令。 556 | 557 | 我们在UNIX下可能会使用不同的Shell,但是make的命令默认是被"/bin/sh"——UNIX的标准Shell解释执行的。除非你特别指定一个其它的Shell。Makefile中,"#"是注释符,很像C/C++中的"//",其后的本行字符都被注释。 558 | 559 | ### 显示命令 560 | 561 | 通常,make会把其要执行的命令行在命令执行前输出到屏幕上。当我们用"@"字符在命令行前,那么,这个命令将不被make显示出来,最具代表性的例子是,我们用这个功能来像屏幕显示一些信息。如: 562 | ```make 563 | @echo 正在编译XXX模块...... 564 | ``` 565 | 当make执行时,会输出"正在编译XXX模块......"字串,但不会输出命令,如果没有"@",那么,make将输出: 566 | ```make 567 | echo 正在编译XXX模块...... 568 | 正在编译XXX模块...... 569 | ``` 570 | 如果make执行时,带入make参数"-n"或"--just-print",那么其只是显示命令,但不会执行命令,这个功能很有利于我们调试我们的Makefile,看看我们书写的命令是执行起来是什么样子的或是什么顺序的。 571 | 572 | 而make参数"-s"或"--slient"则是全面禁止命令的显示。 573 | 574 | ### 命令执行 575 | 576 | 当依赖目标新于目标时,也就是当规则的目标需要被更新时,make会一条一条的执行其后的命令。需要注意的是,如果你要让上一条命令的结果应用在下一条命令时,你应该使用分号分隔这两条命令。比如你的第一条命令是cd命令,你希望第二条命令得在cd之后的基础上运行,那么你就不能把这两条命令写在两行上,而应该把这两条命令写在一行上,用分号分隔。如: 577 | 示例一: 578 | ```make 579 | exec: 580 | cd /home/hchen 581 | pwd 582 | ``` 583 | 示例二: 584 | ```make 585 | exec: 586 | cd /home/hchen; pwd 587 | ``` 588 | 当我们执行"make exec"时,第一个例子中的cd没有作用,pwd会打印出当前的Makefile目录,而第二个例子中,cd就起作用了,pwd会打印出"/home/hchen"。 589 | 590 | make一般是使用环境变量SHELL中所定义的系统Shell来执行命令,默认情况下使用UNIX的标准Shell——/bin/sh来执行命令。但在MS-DOS下有点特殊,因为MS-DOS下没有SHELL环境变量,当然你也可以指定。如果你指定了UNIX风格的目录形式,首先,make会在SHELL所指定的路径中找寻命令解释器,如果找不到,其会在当前盘符中的当前目录中寻找,如果再找不到,其会在PATH环境变量中所定义的所有路径中寻找。MS-DOS中,如果你定义的命令解释器没有找到,其会给你的命令解释器加上诸如".exe"、".com"、".bat"、".sh"等后缀。 591 | 592 | ### 命令出错 593 | 594 | 每当命令运行完后,make会检测每个命令的返回码,如果命令返回成功,那么make会执行下一条命令,当规则中所有的命令成功返回后,这个规则就算是成功完成了。如果一个规则中的某个命令出错了(命令退出码非零),那么make就会终止执行当前规则,这将有可能终止所有规则的执行。 595 | 596 | 有些时候,命令的出错并不表示就是错误的。例如mkdir命令,我们一定需要建立一个目录,如果目录不存在,那么mkdir就成功执行,万事大吉,如果目录存在,那么就出错了。我们之所以使用mkdir的意思就是一定要有这样的一个目录,于是我们就不希望mkdir出错而终止规则的运行。 597 | 598 | 为了做到这一点,忽略命令的出错,我们可以在Makefile的命令行前加一个减号"-"(在Tab键之后),标记为不管命令出不出错都认为是成功的。如: 599 | ```make 600 | clean: 601 | -rm -f *.o 602 | ``` 603 | 还有一个全局的办法是,给make加上"-i"或是"--ignore-errors"参数,那么,Makefile中所有命令都会忽略错误。而如果一个规则是以".IGNORE"作为目标的,那么这个规则中的所有命令将会忽略错误。这些是不同级别的防止命令出错的方法,你可以根据你的不同喜欢设置。 604 | 605 | 还有一个要提一下的make的参数的是"-k"或是"--keep-going",这个参数的意思是,如果某规则中的命令出错了,那么就终目该规则的执行,但继续执行其它规则。 606 | 607 | ### 嵌套执行make 608 | 609 | 在一些大的工程中,我们会把我们不同模块或是不同功能的源文件放在不同的目录中,我们可以在每个目录中都书写一个该目录的Makefile,这有利于让我们的Makefile变得更加地简洁,而不至于把所有的东西全部写在一个Makefile中,这样会很难维护我们的Makefile,这个技术对于我们模块编译和分段编译有着非常大的好处。 610 | 611 | 例如,我们有一个子目录叫subdir,这个目录下有个Makefile文件,来指明了这个目录下文件的编译规则。那么我们总控的Makefile可以这样书写: 612 | ```make 613 | subsystem: 614 | cd subdir && $(MAKE) 615 | ``` 616 | 其等价于: 617 | ```make 618 | subsystem: 619 | $(MAKE) -C subdir 620 | ``` 621 | 定义$(MAKE)宏变量的意思是,也许我们的make需要一些参数,所以定义成一个变量比较利于维护。这两个例子的意思都是先进入"subdir"目录,然后执行make命令。 622 | 623 | 我们把这个Makefile叫做"总控Makefile",总控Makefile的变量可以传递到下级的Makefile中(如果你显示的声明),但是不会覆盖下层的Makefile中所定义的变量,除非指定了"-e"参数。 624 | 625 | 如果你要传递变量到下级Makefile中,那么你可以使用这样的声明: 626 | ```make 627 | export [variable ...] 628 | ``` 629 | 如果你不想让某些变量传递到下级Makefile中,那么你可以这样声明: 630 | ```make 631 | unexport [variable ...] 632 | ``` 633 | 如: 634 | 示例一: 635 | ```make 636 | export variable = value 637 | ``` 638 | 其等价于: 639 | ```make 640 | variable = value 641 | export variable 642 | ``` 643 | 其等价于: 644 | ```make 645 | export variable := value 646 | ``` 647 | 其等价于: 648 | ```make 649 | variable := value 650 | export variable 651 | ``` 652 | 示例二: 653 | ```make 654 | export variable += value 655 | ``` 656 | 其等价于: 657 | ```make 658 | variable += value 659 | export variable 660 | ``` 661 | 如果你要传递所有的变量,那么,只要一个export就行了。后面什么也不用跟,表示传递所有的变量。 662 | 663 | 需要注意的是,有两个变量,一个是SHELL,一个是MAKEFLAGS,这两个变量不管你是否export,其总是要传递到下层Makefile中,特别是MAKEFILES变量,其中包含了make的参数信息,如果我们执行"总控Makefile"时有make参数或是在上层Makefile中定义了这个变量,那么MAKEFILES变量将会是这些参数,并会传递到下层Makefile中,这是一个系统级的环境变量。 664 | 665 | 但是make命令中的有几个参数并不往下传递,它们是"-C","-f","-h""-o"和"-W"(有关Makefile参数的细节将在后面说明),如果你不想往下层传递参数,那么,你可以这样来: 666 | ```make 667 | subsystem: 668 | cd subdir && $(MAKE) MAKEFLAGS= 669 | ``` 670 | 如果你定义了环境变量MAKEFLAGS,那么你得确信其中的选项是大家都会用到的,如果其中有"-t","-n",和"-q"参数,那么将会有让你意想不到的结果,或许会让你异常地恐慌。 671 | 672 | 还有一个在"嵌套执行"中比较有用的参数,"-w"或是"--print-directory"会在make的过程中输出一些信息,让你看到目前的工作目录。比如,如果我们的下级make目录是"/home/hchen/gnu/make",如果我们使用"make -w"来执行,那么当进入该目录时,我们会看到: 673 | ```make 674 | make: Entering directory `/home/hchen/gnu/make'. 675 | ``` 676 | 而在完成下层make后离开目录时,我们会看到: 677 | ```make 678 | make: Leaving directory `/home/hchen/gnu/make' 679 | ``` 680 | 当你使用"-C"参数来指定make下层Makefile时,"-w"会被自动打开的。如果参数中有"-s"("--slient")或是"--no-print-directory",那么,"-w"总是失效的。 681 | 682 | ### 定义命令包 683 | 684 | 如果Makefile中出现一些相同命令序列,那么我们可以为这些相同的命令序列定义一个变量。定义这种命令序列的语法以"define"开始,以"endef"结束,如: 685 | ```make 686 | define run-yacc 687 | yacc $(firstword $^) 688 | mv y.tab.c $@ 689 | endef 690 | ``` 691 | 这里,"run-yacc"是这个命令包的名字,其不要和Makefile中的变量重名。在"define"和"endef"中的两行就是命令序列。这个命令包中的第一个命令是运行Yacc程序,因为Yacc程序总是生成"y.tab.c"的文件,所以第二行的命令就是把这个文件改改名字。还是把这个命令包放到一个示例中来看看吧。 692 | ```make 693 | foo.c: foo.y 694 | $(run-yacc) 695 | ``` 696 | 我们可以看见,要使用这个命令包,我们就好像使用变量一样。在这个命令包的使用中,命令包"run-yacc"中的"$^"就是"foo.y","$@"就是"foo.c"(有关这种以"$"开头的特殊变量,我们会在后面介绍),make在执行命令包时,命令包中的每个命令会被依次独立执行。 697 | 698 | 699 | ## 使用变量 700 | 701 | 在Makefile中的定义的变量,就像是C/C++语言中的宏一样,他代表了一个文本字串,在Makefile中执行的时候其会自动原模原样地展开在所使用的地方。其与C/C++所不同的是,你可以在Makefile中改变其值。在Makefile中,变量可以使用在"目标","依赖目标","命令"或是Makefile的其它部分中。 702 | 703 | 变量的命名字可以包含字符、数字,下划线(可以是数字开头),但不应该含有":"、"#"、"="或是空字符(空格、回车等)。变量是大小写敏感的,"foo"、"Foo"和"FOO"是三个不同的变量名。传统的Makefile的变量名是全大写的命名方式,但我推荐使用大小写搭配的变量名,如:MakeFlags。这样可以避免和系统的变量冲突,而发生意外的事情。 704 | 705 | 有一些变量是很奇怪字串,如"$["、"$@"等,这些是自动化变量,我会在后面介绍。 706 | 707 | ### 变量的基础 708 | 709 | 变量在声明时需要给予初值,而在使用时,需要给在变量名前加上"$"符号,但最好用小括号"()"或是大括号"{}"把变量给包括起来。如果你要使用真实的"$"字符,那么你需要用"$$"来表示。 710 | 711 | 变量可以使用在许多地方,如规则中的"目标"、"依赖"、"命令"以及新的变量中。先看一个例子: 712 | ```make 713 | objects = program.o foo.o utils.o 714 | program: $(objects) 715 | cc -o program $(objects) 716 | 717 | $(objects): defs.h 718 | ``` 719 | 变量会在使用它的地方精确地展开,就像C/C++中的宏一样,例如: 720 | ```make 721 | foo = c 722 | prog.o: prog.$(foo) 723 | $(foo)$(foo) -$(foo) prog.$(foo) 724 | ``` 725 | 展开后得到: 726 | ```make 727 | prog.o: prog.c 728 | cc -c prog.c 729 | ``` 730 | 当然,千万不要在你的Makefile中这样干,这里只是举个例子来表明Makefile中的变量在使用处展开的真实样子。可见其就是一个"替代"的原理。 731 | 732 | 另外,给变量加上括号完全是为了更加安全地使用这个变量,在上面的例子中,如果你不想给变量加上括号,那也可以,但我还是强烈建议你给变量加上括号。 733 | 734 | ### 变量中的变量 735 | 736 | 在定义变量的值时,我们可以使用其它变量来构造变量的值,在Makefile中有两种方式来在用变量定义变量的值。 737 | 738 | 先看第一种方式,也就是简单的使用"="号,在"="左侧是变量,右侧是变量的值,右侧变量的值可以定义在文件的任何一处,也就是说,右侧中的变量不一定非要是已定义好的值,其也可以使用后面定义的值。如: 739 | ```make 740 | foo = $(bar) 741 | bar = $(ugh) 742 | ugh = Huh? 743 | 744 | all: 745 | echo $(foo) 746 | ``` 747 | 我们执行"make all"将会打出变量$(foo)的值是"Huh?"( $(foo)的值是$(bar),$(bar)的值是$(ugh),$(ugh)的值是"Huh?")可见,变量是可以使用后面的变量来定义的。 748 | 749 | 这个功能有好的地方,也有不好的地方,好的地方是,我们可以把变量的真实值推到后面来定义,如: 750 | ```make 751 | CFLAGS = $(include_dirs) -O 752 | include_dirs = -Ifoo -Ibar 753 | ``` 754 | 当"CFLAGS"在命令中被展开时,会是"-Ifoo -Ibar -O"。但这种形式也有不好的地方,那就是递归定义,如: 755 | ```make 756 | CFLAGS = $(CFLAGS) -O 757 | ``` 758 | 或: 759 | ```make 760 | A = $(B) 761 | B = $(A) 762 | ``` 763 | 这会让make陷入无限的变量展开过程中去,当然,我们的make是有能力检测这样的定义,并会报错。还有就是如果在变量中使用函数,那么,这种方式会让我们的make运行时非常慢,更糟糕的是,他会使用得两个make的函数"wildcard"和"shell"发生不可预知的错误。因为你不会知道这两个函数会被调用多少次。 764 | 765 | 为了避免上面的这种方法,我们可以使用make中的另一种用变量来定义变量的方法。这种方法使用的是":="操作符,如: 766 | ```make 767 | x := foo 768 | y := $(x) bar 769 | x := later 770 | ``` 771 | 其等价于: 772 | ```make 773 | y := foo bar 774 | x := later 775 | ``` 776 | 值得一提的是,这种方法,前面的变量不能使用后面的变量,只能使用前面已定义好了的变量。如果是这样: 777 | ```make 778 | y := $(x) bar 779 | x := foo 780 | ``` 781 | 那么,y的值是"bar",而不是"foo bar"。 782 | 783 | 上面都是一些比较简单的变量使用了,让我们来看一个复杂的例子,其中包括了make的函数、条件表达式和一个系统变量"MAKELEVEL"的使用: 784 | ```make 785 | ifeq (0,${MAKELEVEL}) 786 | cur-dir := $(shell pwd) 787 | whoami := $(shell whoami) 788 | host-type := $(shell arch) 789 | MAKE := ${MAKE} host-type=${host-type} whoami=${whoami} 790 | endif 791 | ``` 792 | 关于条件表达式和函数,我们在后面再说,对于系统变量"MAKELEVEL",其意思是,如果我们的make有一个嵌套执行的动作(参见前面的"嵌套使用make"),那么,这个变量会记录了我们的当前Makefile的调用层数。 793 | 794 | 下面再介绍两个定义变量时我们需要知道的,请先看一个例子,如果我们要定义一个变量,其值是一个空格,那么我们可以这样来: 795 | ```make 796 | nullstring := 797 | space := $(nullstring) # end of the line 798 | ``` 799 | nullstring是一个Empty变量,其中什么也没有,而我们的space的值是一个空格。因为在操作符的右边是很难描述一个空格的,这里采用的技术很管用,先用一个Empty变量来标明变量的值开始了,而后面采用"#"注释符来表示变量定义的终止,这样,我们可以定义出其值是一个空格的变量。请注意这里关于"#"的使用,注释符"#"的这种特性值得我们注意,如果我们这样定义一个变量: 800 | ```make 801 | dir := /foo/bar # directory to put the frobs in 802 | ``` 803 | dir这个变量的值是"/foo/bar",后面还跟了4个空格,如果我们这样使用这样变量来指定别的目录——"$(dir)/file"那么就完蛋了。 804 | 805 | 还有一个比较有用的操作符是"?=",先看示例: 806 | ```make 807 | FOO ?= bar 808 | ``` 809 | 其含义是,如果FOO没有被定义过,那么变量FOO的值就是"bar",如果FOO先前被定义过,那么这条语将什么也不做,其等价于: 810 | ```make 811 | ifeq ($(origin FOO), undefined) 812 | FOO = bar 813 | endif 814 | ``` 815 | ### 变量高级用法 816 | 817 | 这里介绍两种变量的高级使用方法,第一种是变量值的替换。 818 | 819 | 我们可以替换变量中的共有的部分,其格式是"$(var:a=b)"或是"${var:a=b}",其意思是,把变量"var"中所有以"a"字串"结尾"的"a"替换成"b"字串。这里的"结尾"意思是"空格"或是"结束符"。 820 | 821 | 还是看一个示例吧: 822 | ```make 823 | foo := a.o b.o c.o 824 | bar := $(foo:.o=.c) 825 | ``` 826 | 这个示例中,我们先定义了一个"$(foo)"变量,而第二行的意思是把"$(foo)"中所有以".o"字串"结尾"全部替换成".c",所以我们的"$(bar)"的值就是"a.c b.c c.c"。 827 | 828 | 另外一种变量替换的技术是以"静态模式"(参见前面章节)定义的,如: 829 | ```make 830 | foo := a.o b.o c.o 831 | bar := $(foo:%.o=%.c) 832 | ``` 833 | 这依赖于被替换字串中的有相同的模式,模式中必须包含一个"%"字符,这个例子同样让$(bar)变量的值为"a.c b.c c.c"。 834 | 835 | 第二种高级用法是——"把变量的值再当成变量"。先看一个例子: 836 | ```make 837 | x = y 838 | y = z 839 | a := $($(x)) 840 | ``` 841 | 在这个例子中,$(x)的值是"y",所以$($(x))就是$(y),于是$(a)的值就是"z"。(注意,是"x=y",而不是"x=$(y)") 842 | 843 | 我们还可以使用更多的层次: 844 | ```make 845 | x = y 846 | y = z 847 | z = u 848 | a := $($($(x))) 849 | ``` 850 | 这里的$(a)的值是"u",相关的推导留给读者自己去做吧。 851 | 852 | 让我们再复杂一点,使用上"在变量定义中使用变量"的第一个方式,来看一个例子: 853 | ```make 854 | x = $(y) 855 | y = z 856 | z = Hello 857 | a := $($(x)) 858 | ``` 859 | 这里的$($(x))被替换成了$($(y)),因为$(y)值是"z",所以,最终结果是:a:=$(z),也就是"Hello"。 860 | 861 | 再复杂一点,我们再加上函数: 862 | ```make 863 | x = variable1 864 | variable2 := Hello 865 | y = $(subst 1,2,$(x)) 866 | z = y 867 | a := $($($(z))) 868 | ``` 869 | 这个例子中,"$($($(z)))"扩展为"$($(y))",而其再次被扩展为"$($(subst 1,2,$(x)))"。$(x)的值是"variable1",subst函数把"variable1"中的所有"1"字串替换成"2"字串,于是,"variable1"变成"variable2",再取其值,所以,最终,$(a)的值就是$(variable2)的值——"Hello"。(喔,好不容易) 870 | 871 | 在这种方式中,或要可以使用多个变量来组成一个变量的名字,然后再取其值: 872 | ```make 873 | first_second = Hello 874 | a = first 875 | b = second 876 | all = $($a_$b) 877 | ``` 878 | 这里的"$a_$b"组成了"first_second",于是,$(all)的值就是"Hello"。 879 | 880 | 再来看看结合第一种技术的例子: 881 | ```make 882 | a_objects := a.o b.o c.o 883 | 1_objects := 1.o 2.o 3.o 884 | 885 | sources := $($(a1)_objects:.o=.c) 886 | ``` 887 | 这个例子中,如果$(a1)的值是"a"的话,那么,$(sources)的值就是"a.c b.c c.c";如果$(a1)的值是"1",那么$(sources)的值是"1.c 2.c 3.c"。 888 | 889 | 再来看一个这种技术和"函数"与"条件语句"一同使用的例子: 890 | ```make 891 | ifdef do_sort 892 | func := sort 893 | else 894 | func := strip 895 | endif 896 | 897 | bar := a d b g q c 898 | 899 | foo := $($(func) $(bar)) 900 | ``` 901 | 这个示例中,如果定义了"do_sort",那么:`foo := $(sort a d b g q c)`,于是$(foo)的值就是"a b c d g q",而如果没有定义"do_sort",那么:`foo := $(sort a d b g q c)`,调用的就是strip函数。 902 | 903 | 当然,"把变量的值再当成变量"这种技术,同样可以用在操作符的左边: 904 | ```make 905 | dir = foo 906 | $(dir)_sources := $(wildcard $(dir)/*.c) 907 | define $(dir)_print 908 | lpr $($(dir)_sources) 909 | endef 910 | ``` 911 | 这个例子中定义了三个变量:"dir","foo_sources"和"foo_print"。 912 | 913 | ### 追加变量值 914 | 915 | 我们可以使用"+="操作符给变量追加值,如: 916 | ```make 917 | objects = main.o foo.o bar.o utils.o 918 | objects += another.o 919 | ``` 920 | 于是,我们的$(objects)值变成:"main.o foo.o bar.o utils.o another.o"(another.o被追加进去了) 921 | 922 | 使用"+="操作符,可以模拟为下面的这种例子: 923 | ```make 924 | objects = main.o foo.o bar.o utils.o 925 | objects := $(objects) another.o 926 | ``` 927 | 所不同的是,用"+="更为简洁。 928 | 929 | 如果变量之前没有定义过,那么,"+="会自动变成"=",如果前面有变量定义,那么"+="会继承于前次操作的赋值符。如果前一次的是":=",那么"+="会以":="作为其赋值符,如: 930 | ```make 931 | variable := value 932 | variable += more 933 | ``` 934 | 等价于: 935 | ```make 936 | variable := value 937 | variable := $(variable) more 938 | ``` 939 | 但如果是这种情况: 940 | ```make 941 | variable = value 942 | variable += more 943 | ``` 944 | 由于前次的赋值符是"=",所以"+="也会以"="来做为赋值,那么岂不会发生变量的递补归定义,这是很不好的,所以make会自动为我们解决这个问题,我们不必担心这个问题。 945 | 946 | ### override 指示符 947 | 948 | 如果有变量是通常make的命令行参数设置的,那么Makefile中对这个变量的赋值会被忽略。如果你想在Makefile中设置这类参数的值,那么,你可以使用"override"指示符。其语法是: 949 | ```make 950 | override [variable] = [value] 951 | override [variable] := [value] 952 | ``` 953 | 当然,你还可以追加: 954 | ```make 955 | override [variable] += [more text] 956 | ``` 957 | 对于多行的变量定义,我们用define指示符,在define指示符前,也同样可以使用ovveride指示符,如: 958 | ```make 959 | override define foo 960 | bar 961 | endef 962 | ``` 963 | 964 | ### 多行变量 965 | 966 | 还有一种设置变量值的方法是使用define关键字。使用define关键字设置变量的值可以有换行,这有利于定义一系列的命令(前面我们讲过"命令包"的技术就是利用这个关键字)。 967 | 968 | define指示符后面跟的是变量的名字,而重起一行定义变量的值,定义是以endef关键字结束。其工作方式和"="操作符一样。变量的值可以包含函数、命令、文字,或是其它变量。因为命令需要以[Tab]键开头,所以如果你用define定义的命令变量中没有以[Tab]键开头,那么make就不会把其认为是命令。 969 | 970 | 下面的这个示例展示了define的用法: 971 | ```make 972 | define two-lines 973 | echo foo 974 | echo $(bar) 975 | endef 976 | ``` 977 | 978 | ### 环境变量 979 | 980 | make运行时的系统环境变量可以在make开始运行时被载入到Makefile文件中,但是如果Makefile中已定义了这个变量,或是这个变量由make命令行带入,那么系统的环境变量的值将被覆盖。(如果make指定了"-e"参数,那么,系统环境变量将覆盖Makefile中定义的变量) 981 | 982 | 因此,如果我们在环境变量中设置了"CFLAGS"环境变量,那么我们就可以在所有的Makefile中使用这个变量了。这对于我们使用统一的编译参数有比较大的好处。如果Makefile中定义了CFLAGS,那么则会使用Makefile中的这个变量,如果没有定义则使用系统环境变量的值,一个共性和个性的统一,很像"全局变量"和"局部变量"的特性。 983 | 984 | 当make嵌套调用时(参见前面的"嵌套调用"章节),上层Makefile中定义的变量会以系统环境变量的方式传递到下层的Makefile中。当然,默认情况下,只有通过命令行设置的变量会被传递。而定义在文件中的变量,如果要向下层Makefile传递,则需要使用exprot关键字来声明。(参见前面章节) 985 | 986 | 当然,我并不推荐把许多的变量都定义在系统环境中,这样,在我们执行不用的Makefile时,拥有的是同一套系统变量,这可能会带来更多的麻烦。 987 | 988 | ### 目标变量 989 | 990 | 前面我们所讲的在Makefile中定义的变量都是"全局变量",在整个文件,我们都可以访问这些变量。当然,"自动化变量"除外,如"$["等这种类量的自动化变量就属于"规则型变量",这种变量的值依赖于规则的目标和依赖目标的定义。 991 | 992 | 当然,我样同样可以为某个目标设置局部变量,这种变量被称为"Target-specific Variable",它可以和"全局变量"同名,因为它的作用范围只在这条规则以及连带规则中,所以其值也只在作用范围内有效。而不会影响规则链以外的全局变量的值。 993 | 994 | 其语法是: 995 | ```make 996 | [target ...]: [variable-assignment] 997 | [target ...]: overide [variable-assignment] 998 | [variable-assignment] 999 | ``` 1000 | 可以是前面讲过的各种赋值表达式,如"="、":="、"+="或是"?="。第二个语法是针对于make命令行带入的变量,或是系统环境变量。 1001 | 1002 | 这个特性非常的有用,当我们设置了这样一个变量,这个变量会作用到由这个目标所引发的所有的规则中去。如: 1003 | ```make 1004 | prog: CFLAGS = -g 1005 | prog: prog.o foo.o bar.o 1006 | $(CC) $(CFLAGS) prog.o foo.o bar.o 1007 | 1008 | prog.o: prog.c 1009 | $(CC) $(CFLAGS) prog.c 1010 | 1011 | foo.o: foo.c 1012 | $(CC) $(CFLAGS) foo.c 1013 | 1014 | bar.o: bar.c 1015 | $(CC) $(CFLAGS) bar.c 1016 | ``` 1017 | 在这个示例中,不管全局的$(CFLAGS)的值是什么,在prog目标,以及其所引发的所有规则中(prog.o foo.o bar.o的规则),$(CFLAGS)的值都是"-g" 1018 | 1019 | ### 模式变量 1020 | 1021 | 在GNU的make中,还支持模式变量(Pattern-specific Variable),通过上面的目标变量中,我们知道,变量可以定义在某个目标上。模式变量的好处就是,我们可以给定一种"模式",可以把变量定义在符合这种模式的所有目标上。 1022 | 1023 | 我们知道,make的"模式"一般是至少含有一个"%"的,所以,我们可以以如下方式给所有以[.o]结尾的目标定义目标变量: 1024 | ```make 1025 | %.o: CFLAGS = -O 1026 | ``` 1027 | 同样,模式变量的语法和"目标变量"一样: 1028 | ```make 1029 | [pattern ...]: [variable-assignment] 1030 | [pattern ...]: override [variable-assignment] 1031 | ``` 1032 | override同样是针对于系统环境传入的变量,或是make命令行指定的变量。 1033 | 1034 | 1035 | ## 使用条件判断 1036 | 1037 | 使用条件判断,可以让make根据运行时的不同情况选择不同的执行分支。条件表达式可以是比较变量的值,或是比较变量和常量的值。 1038 | 1039 | ### 示例 1040 | 1041 | 下面的例子,判断$(CC)变量是否"gcc",如果是的话,则使用GNU函数编译目标。 1042 | ```make 1043 | libs_for_gcc = -lgnu 1044 | normal_libs = 1045 | 1046 | foo: $(objects) 1047 | ifeq ($(CC),gcc) 1048 | $(CC) -o foo $(objects) $(libs_for_gcc) 1049 | else 1050 | $(CC) -o foo $(objects) $(normal_libs) 1051 | endif 1052 | ``` 1053 | 可见,在上面示例的这个规则中,目标"foo"可以根据变量"$(CC)"值来选取不同的函数库来编译程序。 1054 | 1055 | 我们可以从上面的示例中看到三个关键字:ifeq、else和endif。ifeq的意思表示条件语句的开始,并指定一个条件表达式,表达式包含两个参数,以逗号分隔,表达式以圆括号括起。else表示条件表达式为假的情况。endif表示一个条件语句的结束,任何一个条件表达式都应该以endif结束。 1056 | 1057 | 当我们的变量$(CC)值是"gcc"时,目标foo的规则是: 1058 | ```make 1059 | foo: $(objects) 1060 | $(CC) -o foo $(objects) $(libs_for_gcc) 1061 | ``` 1062 | 而当我们的变量$(CC)值不是"gcc"时(比如"cc"),目标foo的规则是: 1063 | ```make 1064 | foo: $(objects) 1065 | $(CC) -o foo $(objects) $(normal_libs) 1066 | ``` 1067 | 当然,我们还可以把上面的那个例子写得更简洁一些: 1068 | ```make 1069 | libs_for_gcc = -lgnu 1070 | normal_libs = 1071 | 1072 | ifeq ($(CC),gcc) 1073 | libs=$(libs_for_gcc) 1074 | else 1075 | libs=$(normal_libs) 1076 | endif 1077 | 1078 | foo: $(objects) 1079 | $(CC) -o foo $(objects) $(libs) 1080 | ``` 1081 | 1082 | ### 语法 1083 | 1084 | 条件表达式的语法为: 1085 | ```make 1086 | [conditional-directive] 1087 | [text-if-true] 1088 | endif 1089 | ``` 1090 | 以及: 1091 | ```make 1092 | [conditional-directive] 1093 | [text-if-true] 1094 | else 1095 | [text-if-false] 1096 | endif 1097 | ``` 1098 | 其中`[conditional-directive]`表示条件关键字,如"ifeq"。这个关键字有四个。 1099 | 1100 | 第一个是我们前面所见过的"ifeq" 1101 | ```make 1102 | ifeq ([arg1], [arg2]) 1103 | ifeq '[arg1]' '[arg2]' 1104 | ifeq "[arg1]" "[arg2]" 1105 | ifeq "[arg1]" '[arg2]' 1106 | ifeq '[arg1]' "[arg2]" 1107 | ``` 1108 | 比较参数"arg1"和"arg2"的值是否相同。当然,参数中我们还可以使用make的函数。如: 1109 | ```make 1110 | ifeq ($(strip $(foo)),) 1111 | [text-if-empty] 1112 | endif 1113 | ``` 1114 | 这个示例中使用了"strip"函数,如果这个函数的返回值是空(Empty),那么[text-if-empty]就生效。 1115 | 1116 | 第二个条件关键字是"ifneq"。语法是: 1117 | ```make 1118 | ifneq ([arg1], [arg2]) 1119 | ifneq '[arg1]' '[arg2]' 1120 | ifneq "[arg1]" "[arg2]" 1121 | ifneq "[arg1]" '[arg2]' 1122 | ifneq '[arg1]' "[arg2]" 1123 | ``` 1124 | 其比较参数"arg1"和"arg2"的值是否相同,如果不同,则为真。和"ifeq"类似。 1125 | 1126 | 第三个条件关键字是"ifdef"。语法是: 1127 | ```make 1128 | ifdef [variable-name] 1129 | ``` 1130 | 如果变量[variable-name]的值非空,那到表达式为真。否则,表达式为假。当然,[variable-name]同样可以是一个函数的返回值。注意,ifdef只是测试一个变量是否有值,其并不会把变量扩展到当前位置。还是来看两个例子: 1131 | 示例一: 1132 | ```make 1133 | bar = 1134 | foo = $(bar) 1135 | ifdef foo 1136 | frobozz = yes 1137 | else 1138 | frobozz = no 1139 | endif 1140 | ``` 1141 | 示例二: 1142 | ```make 1143 | foo = 1144 | ifdef foo 1145 | frobozz = yes 1146 | else 1147 | frobozz = no 1148 | endif 1149 | ``` 1150 | 第一个例子中,"$(frobozz)"值是"yes",第二个则是"no"。 1151 | 1152 | 第四个条件关键字是"ifndef"。其语法是: 1153 | ```make 1154 | ifndef [variable-name] 1155 | ``` 1156 | 这个我就不多说了,和"ifdef"是相反的意思。 1157 | 1158 | 在`[conditional-directive]`这一行上,多余的空格是被允许的,但是不能以[Tab]键做为开始(不然就被认为是命令)。而注释符"#"同样也是安全的。"else"和"endif"也一样,只要不是以[Tab]键开始就行了。 1159 | 1160 | 特别注意的是,make是在读取Makefile时就计算条件表达式的值,并根据条件表达式的值来选择语句,所以,你最好不要把自动化变量(如"$@"等)放入条件表达式中,因为自动化变量是在运行时才有的。 1161 | 1162 | 而且,为了避免混乱,make不允许把整个条件语句分成两部分放在不同的文件中。 1163 | 1164 | 1165 | ## 使用函数 1166 | 1167 | 在Makefile中可以使用函数来处理变量,从而让我们的命令或是规则更为的灵活和具有智能。make所支持的函数也不算很多,不过已经足够我们的操作了。函数调用后,函数的返回值可以当做变量来使用。 1168 | 1169 | ### 函数的调用语法 1170 | 1171 | 函数调用,很像变量的使用,也是以"$"来标识的,其语法如下: 1172 | ```make 1173 | $([function] [arguments]) 1174 | ``` 1175 | 或是 1176 | ```make 1177 | ${[function] [arguments]} 1178 | ``` 1179 | 这里,[function]就是函数名,make支持的函数不多。[arguments]是函数的参数,参数间以逗号","分隔,而函数名和参数之间以"空格"分隔。函数调用以"$"开头,以圆括号或花括号把函数名和参数括起。感觉很像一个变量,是不是?函数中的参数可以使用变量,为了风格的统一,函数和变量的括号最好一样,如使用"$(subst a,b,$(x))"这样的形式,而不是"$(subst a,b,${x})"的形式。因为统一会更清楚,也会减少一些不必要的麻烦。 1180 | 1181 | 还是来看一个示例: 1182 | ```make 1183 | comma:= , 1184 | empty:= 1185 | space:= $(empty) $(empty) 1186 | foo:= a b c 1187 | bar:= $(subst $(space),$(comma),$(foo)) 1188 | ``` 1189 | 在这个示例中,$(comma)的值是一个逗号。$(space)使用了$(empty)定义了一个空格,$(foo)的值是"a b c",$(bar)的定义用,调用了函数"subst",这是一个替换函数,这个函数有三个参数,第一个参数是被替换字串,第二个参数是替换字串,第三个参数是替换操作作用的字串。这个函数也就是把$(foo)中的空格替换成逗号,所以$(bar)的值是"a,b,c"。 1190 | 1191 | ### 字符串处理函数 1192 | 1193 | ```make 1194 | $(subst [from],[to],[text]) 1195 | ``` 1196 | 名称:字符串替换函数——subst。 1197 | 功能:把字串[text]中的[from]字符串替换成[to]。 1198 | 返回:函数返回被替换过后的字符串。 1199 | 示例: 1200 | ```make 1201 | $(subst ee,EE,feet on the street), 1202 | ``` 1203 | 把"feet on the street"中的"ee"替换成"EE",返回结果是"fEEt on the strEEt"。 1204 | 1205 | 1206 | ```make 1207 | $(patsubst [pattern],[replacement],[text]) 1208 | ``` 1209 | 名称:模式字符串替换函数——patsubst。 1210 | 功能:查找[text]中的单词(单词以"空格"、"Tab"或"回车""换行"分隔)是否符合模式[pattern],如果匹配的话,则以[replacement]替换。这里,[pattern]可以包括通配符"%",表示任意长度的字串。如果[replacement]中也包含"%",那么,[replacement]中的这个"%"将是[pattern]中的那个"%"所代表的字串。(可以用"/"来转义,以"/%"来表示真实含义的"%"字符) 1211 | 返回:函数返回被替换过后的字符串。 1212 | 示例: 1213 | ```make 1214 | $(patsubst %.c,%.o,x.c.c bar.c) 1215 | ``` 1216 | 把字串"x.c.c bar.c"符合模式[%.c]的单词替换成[%.o],返回结果是"x.c.o bar.o" 1217 | 备注:这和我们前面"变量章节"说过的相关知识有点相似。如:"$(var:[pattern]=[replacement])", 相当于"$(patsubst [pattern],[replacement],$(var))",而"$(var: [suffix]=[replacement])", 则相当于"$(patsubst %[suffix],%[replacement],$(var))"。 1218 | 例如有:objects = foo.o bar.o baz.o,那么,"$(objects:.o=.c)"和"$(patsubst %.o,%.c,$(objects))"是一样的。 1219 | 1220 | 1221 | ```make 1222 | $(strip [string]) 1223 | ``` 1224 | 名称:去空格函数——strip。 1225 | 功能:去掉[string]字串中开头和结尾的空字符。 1226 | 返回:返回被去掉空格的字符串值。 1227 | 示例: 1228 | ```make 1229 | $(strip a b c ) 1230 | ``` 1231 | 把字串"a b c "去到开头和结尾的空格,结果是"a b c"。 1232 | 1233 | 1234 | ```make 1235 | $(findstring [find],[in]) 1236 | ``` 1237 | 名称:查找字符串函数——findstring。 1238 | 功能:在字串[in]中查找[find]字串。 1239 | 返回:如果找到,那么返回[find],否则返回空字符串。 1240 | 示例: 1241 | ```make 1242 | $(findstring a,a b c) 1243 | $(findstring a,b c) 1244 | ``` 1245 | 第一个函数返回"a"字符串,第二个返回""字符串(空字符串) 1246 | 1247 | 1248 | ```make 1249 | $(filter [pattern...],[text]) 1250 | ``` 1251 | 名称:过滤函数——filter。 1252 | 功能:以[pattern]模式过滤[text]字符串中的单词,保留符合模式[pattern]的单词。可以有多个模式。 1253 | 返回:返回符合模式[pattern]的字串。 1254 | 示例: 1255 | ```make 1256 | sources := foo.c bar.c baz.s ugh.h 1257 | foo: $(sources) 1258 | cc $(filter %.c %.s,$(sources)) -o foo 1259 | 1260 | $(filter %.c %.s,$(sources)) 1261 | ``` 1262 | 返回的值是"foo.c bar.c baz.s"。 1263 | 1264 | 1265 | ```make 1266 | $(filter-out [pattern...],[text]) 1267 | ``` 1268 | 名称:反过滤函数——filter-out。 1269 | 功能:以[pattern]模式过滤[text]字符串中的单词,去除符合模式[pattern]的单词。可以有多个模式。 1270 | 返回:返回不符合模式[pattern]的字串。 1271 | 示例: 1272 | ```make 1273 | objects=main1.o foo.o main2.o bar.o 1274 | mains=main1.o main2.o 1275 | 1276 | $(filter-out $(mains),$(objects)) 1277 | ``` 1278 | 返回值是"foo.o bar.o"。 1279 | 1280 | 1281 | ```make 1282 | $(sort [list]) 1283 | ``` 1284 | 名称:排序函数——sort。 1285 | 功能:给字符串[list]中的单词排序(升序)。 1286 | 返回:返回排序后的字符串。 1287 | 示例:$(sort foo bar lose)返回"bar foo lose" 。 1288 | 备注:sort函数会去掉[list]中相同的单词。 1289 | 1290 | 1291 | ```make 1292 | $(word [n],[text]) 1293 | ``` 1294 | 名称:取单词函数——word。 1295 | 功能:取字符串[text]中第[n]个单词。(从一开始) 1296 | 返回:返回字符串[text]中第[n]个单词。如果[n]比[text]中的单词数要大,那么返回空字符串。 1297 | 示例:$(word 2, foo bar baz)返回值是"bar"。 1298 | 1299 | 1300 | ```make 1301 | $(wordlist [s],[e],[text]) 1302 | ``` 1303 | 名称:取单词串函数——wordlist。 1304 | 功能:从字符串[text]中取从[s]开始到[e]的单词串。[s]和[e]是一个数字。 1305 | 返回:返回字符串[text]中从[s]到[e]的单词字串。如果[s]比[text]中的单词数要大,那么返回空字符串。如果[e]大于[text]的单词数,那么返回从[s]开始,到[text]结束的单词串。 1306 | 示例: $(wordlist 2, 3, foo bar baz)返回值是"bar baz"。 1307 | 1308 | 1309 | ```make 1310 | $(words [text]) 1311 | ``` 1312 | 名称:单词个数统计函数——words。 1313 | 功能:统计[text]中字符串中的单词个数。 1314 | 返回:返回[text]中的单词数。 1315 | 示例:$(words, foo bar baz)返回值是"3"。 1316 | 备注:如果我们要取[text]中最后的一个单词,我们可以这样:$(word $(words [text]),[text])。 1317 | 1318 | 1319 | ```make 1320 | $(firstword [text]) 1321 | ``` 1322 | 名称:首单词函数——firstword。 1323 | 功能:取字符串[text]中的第一个单词。 1324 | 返回:返回字符串[text]的第一个单词。 1325 | 示例:$(firstword foo bar)返回值是"foo"。 1326 | 备注:这个函数可以用word函数来实现:$(word 1,[text])。 1327 | 1328 | 以上,是所有的字符串操作函数,如果搭配混合使用,可以完成比较复杂的功能。这里,举一个现实中应用的例子。我们知道,make使用"VPATH"变量来指定"依赖文件"的搜索路径。于是,我们可以利用这个搜索路径来指定编译器对头文件的搜索路径参数CFLAGS,如: 1329 | ```make 1330 | override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH))) 1331 | ``` 1332 | 如果我们的"$(VPATH)"值是"src:../headers",那么"$(patsubst %,-I%,$(subst :, ,$(VPATH)))"将返回"-Isrc -I../headers",这正是cc或gcc搜索头文件路径的参数。 1333 | 1334 | ### 文件名操作函数 1335 | 1336 | 下面我们要介绍的函数主要是处理文件名的。每个函数的参数字符串都会被当做一个或是一系列的文件名来对待。 1337 | 1338 | ```make 1339 | $(dir [names...]) 1340 | ``` 1341 | 名称:取目录函数——dir。 1342 | 功能:从文件名序列[names]中取出目录部分。目录部分是指最后一个反斜杠("/")之前的部分。如果没有反斜杠,那么返回"./"。 1343 | 返回:返回文件名序列[names]的目录部分。 1344 | 示例: $(dir src/foo.c hacks)返回值是"src/ ./"。 1345 | 1346 | 1347 | ```make 1348 | $(notdir [names...]) 1349 | ``` 1350 | 名称:取文件函数——notdir。 1351 | 功能:从文件名序列[names]中取出非目录部分。非目录部分是指最后一个反斜杠("/")之后的部分。 1352 | 返回:返回文件名序列[names]的非目录部分。 1353 | 示例: $(notdir src/foo.c hacks)返回值是"foo.c hacks"。 1354 | 1355 | 1356 | ```make 1357 | $(suffix [names...]) 1358 | ``` 1359 | 名称:取后缀函数——suffix。 1360 | 功能:从文件名序列[names]中取出各个文件名的后缀。 1361 | 返回:返回文件名序列[names]的后缀序列,如果文件没有后缀,则返回空字串。 1362 | 示例:$(suffix src/foo.c src-1.0/bar.c hacks)返回值是".c .c"。 1363 | 1364 | 1365 | ```make 1366 | $(basename [names...]) 1367 | ``` 1368 | 名称:取前缀函数——basename。 1369 | 功能:从文件名序列[names]中取出各个文件名的前缀部分。 1370 | 返回:返回文件名序列[names]的前缀序列,如果文件没有前缀,则返回空字串。 1371 | 示例:$(basename src/foo.c src-1.0/bar.c hacks)返回值是"src/foo src-1.0/bar hacks"。 1372 | 1373 | 1374 | ```make 1375 | $(addsuffix [suffix],[names...]) 1376 | ``` 1377 | 名称:加后缀函数——addsuffix。 1378 | 功能:把后缀[suffix]加到[names]中的每个单词后面。 1379 | 返回:返回加过后缀的文件名序列。 1380 | 示例:$(addsuffix .c,foo bar)返回值是"foo.c bar.c"。 1381 | 1382 | 1383 | ```make 1384 | $(addprefix [prefix],[names...]) 1385 | ``` 1386 | 名称:加前缀函数——addprefix。 1387 | 功能:把前缀[prefix]加到[names]中的每个单词后面。 1388 | 返回:返回加过前缀的文件名序列。 1389 | 示例:$(addprefix src/,foo bar)返回值是"src/foo src/bar"。 1390 | 1391 | 1392 | ```make 1393 | $(join [list1],[list2]) 1394 | ``` 1395 | 名称:连接函数——join。 1396 | 功能:把[list2]中的单词对应地加到[list1]的单词后面。如果[list1]的单词个数要比[list2]的多,那么,[list1]中的多出来的单词将保持原样。如果[list2]的单词个数要比[list1]多,那么,[list2]多出来的单词将被复制到[list2]中。 1397 | 返回:返回连接过后的字符串。 1398 | 示例:$(join aaa bbb , 111 222 333)返回值是"aaa111 bbb222 333"。 1399 | 1400 | ### foreach 函数 1401 | 1402 | foreach函数和别的函数非常的不一样。因为这个函数是用来做循环用的,Makefile中的foreach函数几乎是仿照于Unix标准Shell(/bin/sh)中的for语句,或是C-Shell(/bin/csh)中的foreach语句而构建的。它的语法是: 1403 | ```make 1404 | $(foreach [var],[list],[text]) 1405 | ``` 1406 | 这个函数的意思是,把参数[list]中的单词逐一取出放到参数[var]所指定的变量中,然后再执行[text]所包含的表达式。每一次[text]会返回一个字符串,循环过程中,[text]的所返回的每个字符串会以空格分隔,最后当整个循环结束时,[text]所返回的每个字符串所组成的整个字符串(以空格分隔)将会是foreach函数的返回值。 1407 | 1408 | 所以,[var]最好是一个变量名,[list]可以是一个表达式,而[text]中一般会使用[var]这个参数来依次枚举[list]中的单词。举个例子: 1409 | ```make 1410 | names := a b c d 1411 | files := $(foreach n,$(names),$(n).o) 1412 | ``` 1413 | 上面的例子中,$(name)中的单词会被挨个取出,并存到变量"n"中,"$(n).o"每次根据"$(n)"计算出一个值,这些值以空格分隔,最后作为foreach函数的返回,所以,$(files)的值是"a.o b.o c.o d.o"。 1414 | 1415 | 注意,foreach中的[var]参数是一个临时的局部变量,foreach函数执行完后,参数[var]的变量将不在作用,其作用域只在foreach函数当中。 1416 | 1417 | ### if 函数 1418 | 1419 | if函数很像GNU的make所支持的条件语句——ifeq(参见前面所述的章节),if函数的语法是: 1420 | ```make 1421 | $(if [condition],[then-part]) 1422 | ``` 1423 | 或是 1424 | ```make 1425 | $(if [condition],[then-part],[else-part]) 1426 | ``` 1427 | 可见,if函数可以包含"else"部分,或是不含。即if函数的参数可以是两个,也可以是三个。[condition]参数是if的表达式,如果其返回的为非空字符串,那么这个表达式就相当于返回真,于是,[then-part]会被计算,否则[else-part]会被计算。 1428 | 1429 | 而if函数的返回值是,如果[condition]为真(非空字符串),那个[then-part]会是整个函数的返回值,如果[condition]为假(空字符串),那么[else-part]会是整个函数的返回值,此时如果[else-part]没有被定义,那么,整个函数返回空字串。 1430 | 1431 | 所以,[then-part]和[else-part]只会有一个被计算。 1432 | 1433 | ### call函数 1434 | 1435 | call函数是唯一一个可以用来创建新的参数化的函数。你可以写一个非常复杂的表达式,这个表达式中,你可以定义许多参数,然后你可以用call函数来向这个表达式传递参数。其语法是: 1436 | ```make 1437 | $(call [expression],[parm1],[parm2],[parm3]...) 1438 | ``` 1439 | 当make执行这个函数时,[expression]参数中的变量,如$(1),$(2),$(3)等,会被参数[parm1],[parm2],[parm3]依次取代。而[expression]的返回值就是call函数的返回值。例如: 1440 | ```make 1441 | reverse = $(1) $(2) 1442 | foo = $(call reverse,a,b) 1443 | ``` 1444 | 那么,foo的值就是"a b"。当然,参数的次序是可以自定义的,不一定是顺序的,如: 1445 | ```make 1446 | reverse = $(2) $(1) 1447 | foo = $(call reverse,a,b) 1448 | ``` 1449 | 此时的foo的值就是"b a"。 1450 | 1451 | ### origin函数 1452 | 1453 | origin函数不像其它的函数,他并不操作变量的值,他只是告诉你你的这个变量是哪里来的?其语法是: 1454 | ```make 1455 | $(origin [variable]) 1456 | ``` 1457 | 注意,[variable]是变量的名字,不应该是引用。所以你最好不要在[variable]中使用"$"字符。Origin函数会以其返回值来告诉你这个变量的"出生情况",下面,是origin函数的返回值: 1458 | + "undefined" 如果[variable]从来没有定义过,origin函数返回这个值"undefined"。 1459 | + "default" 如果[variable]是一个默认的定义,比如"CC"这个变量,这种变量我们将在后面讲述。 1460 | + "environment" 如果[variable]是一个环境变量,并且当Makefile被执行时,"-e"参数没有被打开。 1461 | + "file" 如果[variable]这个变量被定义在Makefile中。 1462 | + "command line" 如果[variable]这个变量是被命令行定义的。 1463 | + "override" 如果[variable]是被override指示符重新定义的。 1464 | + "automatic" 如果[variable]是一个命令运行中的自动化变量。关于自动化变量将在后面讲述。 1465 | 1466 | 这些信息对于我们编写Makefile是非常有用的,例如,假设我们有一个Makefile其包了一个定义文件Make.def,在Make.def中定义了一个变量"bletch",而我们的环境中也有一个环境变量"bletch",此时,我们想判断一下,如果变量来源于环境,那么我们就把之重定义了,如果来源于Make.def或是命令行等非环境的,那么我们就不重新定义它。于是,在我们的Makefile中,我们可以这样写: 1467 | ```make 1468 | ifdef bletch 1469 | ifeq "$(origin bletch)" "environment" 1470 | bletch = barf, gag, etc. 1471 | endif 1472 | endif 1473 | ``` 1474 | 当然,你也许会说,使用override关键字不就可以重新定义环境中的变量了吗?为什么需要使用这样的步骤?是的,我们用override是可以达到这样的效果,可是override过于粗暴,它同时会把从命令行定义的变量也覆盖了,而我们只想重新定义环境传来的,而不想重新定义命令行传来的。 1475 | 1476 | ### shell函数 1477 | 1478 | shell函数也不像其它的函数。顾名思义,它的参数应该就是操作系统Shell的命令。它和反引号"`"是相同的功能。这就是说,shell函数把执行操作系统命令后的输出作为函数返回。于是,我们可以用操作系统命令以及字符串处理命令awk,sed等等命令来生成一个变量,如: 1479 | ```make 1480 | contents := $(shell cat foo) 1481 | 1482 | files := $(shell echo *.c) 1483 | ``` 1484 | 注意,这个函数会新生成一个Shell程序来执行命令,所以你要注意其运行性能,如果你的Makefile中有一些比较复杂的规则,并大量使用了这个函数,那么对于你的系统性能是有害的。特别是Makefile的隐晦的规则可能会让你的shell函数执行的次数比你想像的多得多。 1485 | 1486 | ### 控制make的函数 1487 | 1488 | make提供了一些函数来控制make的运行。通常,你需要检测一些运行Makefile时的运行时信息,并且根据这些信息来决定,你是让make继续执行,还是停止。 1489 | 1490 | ```make 1491 | $(error [text ...]) 1492 | ``` 1493 | 产生一个致命的错误,[text ...]是错误信息。注意,error函数不会在一被使用就会产生错误信息,所以如果你把其定义在某个变量中,并在后续的脚本中使用这个变量,那么也是可以的。例如: 1494 | 示例一: 1495 | ```make 1496 | ifdef ERROR_001 1497 | $(error error is $(ERROR_001)) 1498 | endif 1499 | ``` 1500 | 示例二: 1501 | ```make 1502 | ERR = $(error found an error!) 1503 | .PHONY: err 1504 | err: ; $(ERR) 1505 | ``` 1506 | 示例一会在变量ERROR_001定义了后执行时产生error调用,而示例二则在目录err被执行时才发生error调用。 1507 | 1508 | 1509 | ```make 1510 | $(warning [text ...]) 1511 | ``` 1512 | 这个函数很像error函数,只是它并不会让make退出,只是输出一段警告信息,而make继续执行。 1513 | 1514 | 1515 | ## make 的运行 1516 | 1517 | 一般来说,最简单的就是直接在命令行下输入make命令,make命令会找当前目录的makefile来执行,一切都是自动的。但也有时你也许只想让make重编译某些文件,而不是整个工程,而又有的时候你有几套编译规则,你想在不同的时候使用不同的编译规则,等等。本章节就是讲述如何使用make命令的。 1518 | 1519 | ### make的退出码 1520 | 1521 | make命令执行后有三个退出码: 1522 | + 0 —— 表示成功执行。 1523 | + 1 —— 如果make运行时出现任何错误,其返回1。 1524 | + 2 —— 如果你使用了make的"-q"选项,并且make使得一些目标不需要更新,那么返回2。 1525 | 1526 | Make的相关参数我们会在后续章节中讲述。 1527 | 1528 | ### 指定Makefile 1529 | 1530 | 前面我们说过,GNU make找寻默认的Makefile的规则是在当前目录下依次找三个文件——"GNUmakefile"、"makefile"和"Makefile"。其按顺序找这三个文件,一旦找到,就开始读取这个文件并执行。 1531 | 1532 | 当前,我们也可以给make命令指定一个特殊名字的Makefile。要达到这个功能,我们要使用make的"-f"或是"--file"参数("--makefile"参数也行)。例如,我们有个makefile的名字是"hchen.mk",那么,我们可以这样来让make来执行这个文件: 1533 | ```make 1534 | make –f hchen.mk 1535 | ``` 1536 | 如果在make的命令行是,你不只一次地使用了"-f"参数,那么,所有指定的makefile将会被连在一起传递给make执行。 1537 | 1538 | ### 指定目标 1539 | 1540 | 一般来说,make的最终目标是makefile中的第一个目标,而其它目标一般是由这个目标连带出来的。这是make的默认行为。当然,一般来说,你的makefile中的第一个目标是由许多个目标组成,你可以指示make,让其完成你所指定的目标。要达到这一目的很简单,需在make命令后直接跟目标的名字就可以完成(如前面提到的"make clean"形式) 1541 | 1542 | 任何在makefile中的目标都可以被指定成终极目标,但是除了以"-"打头,或是包含了"="的目标,因为有这些字符的目标,会被解析成命令行参数或是变量。甚至没有被我们明确写出来的目标也可以成为make的终极目标,也就是说,只要make可以找到其隐含规则推导规则,那么这个隐含目标同样可以被指定成终极目标。 1543 | 1544 | 有一个make的环境变量叫"MAKECMDGOALS",这个变量中会存放你所指定的终极目标的列表,如果在命令行上,你没有指定目标,那么,这个变量是空值。这个变量可以让你使用在一些比较特殊的情形下。比如下面的例子: 1545 | ```make 1546 | sources = foo.c bar.c 1547 | ifneq ( $(MAKECMDGOALS),clean) 1548 | include $(sources:.c=.d) 1549 | endif 1550 | ``` 1551 | 基于上面的这个例子,只要我们输入的命令不是"make clean",那么makefile会自动包含"foo.d"和"bar.d"这两个makefile。 1552 | 1553 | 使用指定终极目标的方法可以很方便地让我们编译我们的程序,例如下面这个例子: 1554 | ```make 1555 | .PHONY: all 1556 | all: prog1 prog2 prog3 prog4 1557 | ``` 1558 | 从这个例子中,我们可以看到,这个makefile中有四个需要编译的程序——"prog1", "prog2", "prog3"和 "prog4",我们可以使用"make all"命令来编译所有的目标(如果把all置成第一个目标,那么只需执行"make"),我们也可以使用"make prog2"来单独编译目标"prog2"。 1559 | 1560 | 即然make可以指定所有makefile中的目标,那么也包括"伪目标",于是我们可以根据这种性质来让我们的makefile根据指定的不同的目标来完成不同的事。在Unix世界中,软件发布时,特别是GNU这种开源软件的发布时,其makefile都包含了编译、安装、打包等功能。我们可以参照这种规则来书写我们的makefile中的目标。 1561 | 1562 | + "all" 这个伪目标是所有目标的目标,其功能一般是编译所有的目标。 1563 | + "clean" 这个伪目标功能是删除所有被make创建的文件。 1564 | + "install" 这个伪目标功能是安装已编译好的程序,其实就是把目标执行文件拷贝到指定的目标中去。 1565 | + "print" 这个伪目标的功能是例出改变过的源文件。 1566 | + "tar" 这个伪目标功能是把源程序打包备份。也就是一个tar文件。 1567 | + "dist" 这个伪目标功能是创建一个压缩文件,一般是把tar文件压成Z文件。或是gz文件。 1568 | + "TAGS" 这个伪目标功能是更新所有的目标,以备完整地重编译使用。 1569 | + "check"和"test" 这两个伪目标一般用来测试makefile的流程。 1570 | 1571 | 当然一个项目的makefile中也不一定要书写这样的目标,这些东西都是GNU的东西,但是我想,GNU搞出这些东西一定有其可取之处(等你的UNIX下的程序文件一多时你就会发现这些功能很有用了),这里只不过是说明了,如果你要书写这种功能,最好使用这种名字命名你的目标,这样规范一些,规范的好处就是——不用解释,大家都明白。而且如果你的makefile中有这些功能,一是很实用,二是可以显得你的makefile很专业(不是那种初学者的作品)。 1572 | 1573 | ### 检查规则 1574 | 1575 | 有时候,我们不想让我们的makefile中的规则执行起来,我们只想检查一下我们的命令,或是执行的序列。于是我们可以使用make命令的下述参数: 1576 | "-n" 1577 | "--just-print" 1578 | "--dry-run" 1579 | "--recon" 1580 | 不执行参数,这些参数只是打印命令,不管目标是否更新,把规则和连带规则下的命令打印出来,但不执行,这些参数对于我们调试makefile很有用处。 1581 | 1582 | "-t" 1583 | "--touch" 1584 | 这个参数的意思就是把目标文件的时间更新,但不更改目标文件。也就是说,make假装编译目标,但不是真正的编译目标,只是把目标变成已编译过的状态。 1585 | 1586 | "-q" 1587 | "--question" 1588 | 这个参数的行为是找目标的意思,也就是说,如果目标存在,那么其什么也不会输出,当然也不会执行编译,如果目标不存在,其会打印出一条出错信息。 1589 | 1590 | "-W [file]" 1591 | "--what-if=[file]" 1592 | "--assume-new=[file]" 1593 | "--new-file=[file]" 1594 | 这个参数需要指定一个文件。一般是是源文件(或依赖文件),Make会根据规则推导来运行依赖于这个文件的命令,一般来说,可以和"-n"参数一同使用,来查看这个依赖文件所发生的规则命令。 1595 | 1596 | 另外一个很有意思的用法是结合"-p"和"-v"来输出makefile被执行时的信息(这个将在后面讲述)。 1597 | 1598 | ### make的参数 1599 | 1600 | 下面列举了所有GNU make 3.80版的参数定义。其它版本和产商的make大同小异,不过其它产商的make的具体参数还是请参考各自的产品文档。 1601 | 1602 | "-b" 1603 | "-m" 1604 | 这两个参数的作用是忽略和其它版本make的兼容性。 1605 | 1606 | "-B" 1607 | "--always-make" 1608 | 认为所有的目标都需要更新(重编译)。 1609 | 1610 | "-C [dir]" 1611 | "--directory=[dir]" 1612 | 指定读取makefile的目录。如果有多个"-C"参数,make的解释是后面的路径以前面的作为相对路径,并以最后的目录作为被指定目录。如:"make –C ~hchen/test –C prog"等价于"make –C ~hchen/test/prog"。 1613 | 1614 | "—debug[=[options]]" 1615 | 输出make的调试信息。它有几种不同的级别可供选择,如果没有参数,那就是输出最简单的调试信息。下面是[options]的取值: 1616 | 1617 | + a —— 也就是all,输出所有的调试信息。(会非常的多) 1618 | + b —— 也就是basic,只输出简单的调试信息。即输出不需要重编译的目标。 1619 | + v —— 也就是verbose,在b选项的级别之上。输出的信息包括哪个makefile被解析,不需要被重编译的依赖文件(或是依赖目标)等。 1620 | + i —— 也就是implicit,输出所以的隐含规则。 1621 | + j —— 也就是jobs,输出执行规则中命令的详细信息,如命令的PID、返回码等。 1622 | + m —— 也就是makefile,输出make读取makefile,更新makefile,执行makefile的信息。 1623 | 1624 | "-d" 1625 | 相当于"--debug=a"。 1626 | 1627 | "-e" 1628 | "--environment-overrides" 1629 | 指明环境变量的值覆盖makefile中定义的变量的值。 1630 | 1631 | "-f=[file]" 1632 | "--file=[file]" 1633 | "--makefile=[file]" 1634 | 指定需要执行的makefile。 1635 | 1636 | "-h" 1637 | "--help" 1638 | 显示帮助信息。 1639 | 1640 | "-i" 1641 | "--ignore-errors" 1642 | 在执行时忽略所有的错误。 1643 | 1644 | "-I [dir]" 1645 | "--include-dir=[dir]" 1646 | 指定一个被包含makefile的搜索目标。可以使用多个"-I"参数来指定多个目录。 1647 | 1648 | "-j [[jobsnum]]" 1649 | "--jobs[=[jobsnum]]" 1650 | 指同时运行命令的个数。如果没有这个参数,make运行命令时能运行多少就运行多少。如果有一个以上的"-j"参数,那么仅最后一个"-j"才是有效的。(注意这个参数在MS-DOS中是无用的) 1651 | 1652 | "-k" 1653 | "--keep-going" 1654 | 出错也不停止运行。如果生成一个目标失败了,那么依赖于其上的目标就不会被执行了。 1655 | 1656 | "-l [load]" 1657 | "--load-average[=[load]" 1658 | "—max-load[=[load]]" 1659 | 指定make运行命令的负载。 1660 | 1661 | "-n" 1662 | "--just-print" 1663 | "--dry-run" 1664 | "--recon" 1665 | 仅输出执行过程中的命令序列,但并不执行。 1666 | 1667 | "-o [file]" 1668 | "--old-file=[file]" 1669 | "--assume-old=[file]" 1670 | 不重新生成的指定的[file],即使这个目标的依赖文件新于它。 1671 | 1672 | "-p" 1673 | "--print-data-base" 1674 | 输出makefile中的所有数据,包括所有的规则和变量。这个参数会让一个简单的makefile都会输出一堆信息。如果你只是想输出信息而不想执行makefile,你可以使用"make -qp"命令。如果你想查看执行makefile前的预设变量和规则,你可以使用"make –p –f /dev/null"。这个参数输出的信息会包含着你的makefile文件的文件名和行号,所以,用这个参数来调试你的makefile会是很有用的,特别是当你的环境变量很复杂的时候。 1675 | 1676 | "-q" 1677 | "--question" 1678 | 不运行命令,也不输出。仅仅是检查所指定的目标是否需要更新。如果是0则说明要更新,如果是2则说明有错误发生。 1679 | 1680 | "-r" 1681 | "--no-builtin-rules" 1682 | 禁止make使用任何隐含规则。 1683 | 1684 | "-R" 1685 | "--no-builtin-variabes" 1686 | 禁止make使用任何作用于变量上的隐含规则。 1687 | 1688 | "-s" 1689 | "--silent" 1690 | "--quiet" 1691 | 在命令运行时不输出命令的输出。 1692 | 1693 | "-S" 1694 | "--no-keep-going" 1695 | "--stop" 1696 | 取消"-k"选项的作用。因为有些时候,make的选项是从环境变量"MAKEFLAGS"中继承下来的。所以你可以在命令行中使用这个参数来让环境变量中的"-k"选项失效。 1697 | 1698 | "-t" 1699 | "--touch" 1700 | 相当于UNIX的touch命令,只是把目标的修改日期变成最新的,也就是阻止生成目标的命令运行。 1701 | 1702 | "-v" 1703 | "--version" 1704 | 输出make程序的版本、版权等关于make的信息。 1705 | 1706 | "-w" 1707 | "--print-directory" 1708 | 输出运行makefile之前和之后的信息。这个参数对于跟踪嵌套式调用make时很有用。 1709 | 1710 | "--no-print-directory" 1711 | 禁止"-w"选项。 1712 | 1713 | "-W [file]" 1714 | "--what-if=[file]" 1715 | "--new-file=[file]" 1716 | "--assume-file=[file]" 1717 | 假定目标[file]需要更新,如果和"-n"选项使用,那么这个参数会输出该目标更新时的运行动作。如果没有"-n"那么就像运行UNIX的"touch"命令一样,使得[file]的修改时间为当前时间。 1718 | 1719 | "--warn-undefined-variables" 1720 | 只要make发现有未定义的变量,那么就输出警告信息。 1721 | 1722 | 1723 | ## 隐含规则 1724 | 1725 | 在我们使用Makefile时,有一些我们会经常使用,而且使用频率非常高的东西,比如,我们编译C/C++的源程序为中间目标文件(Unix下是[.o]文件,Windows下是[.obj]文件)。本章讲述的就是一些在Makefile中的"隐含的",早先约定了的,不需要我们再写出来的规则。 1726 | 1727 | "隐含规则"也就是一种惯例,make会按照这种"惯例"心照不喧地来运行,那怕我们的Makefile中没有书写这样的规则。例如,把[.c]文件编译成[.o]文件这一规则,你根本就不用写出来,make会自动推导出这种规则,并生成我们需要的[.o]文件。 1728 | 1729 | "隐含规则"会使用一些我们系统变量,我们可以改变这些系统变量的值来定制隐含规则的运行时的参数。如系统变量"CFLAGS"可以控制编译时的编译器参数。 1730 | 1731 | 我们还可以通过"模式规则"的方式写下自己的隐含规则。用"后缀规则"来定义隐含规则会有许多的限制。使用"模式规则"会更回得智能和清楚,但"后缀规则"可以用来保证我们Makefile的兼容性。 1732 | 我们了解了"隐含规则",可以让其为我们更好的服务,也会让我们知道一些"约定俗成"了的东西,而不至于使得我们在运行Makefile时出现一些我们觉得莫名其妙的东西。当然,任何事物都是矛盾的,水能载舟,亦可覆舟,所以,有时候"隐含规则"也会给我们造成不小的麻烦。只有了解了它,我们才能更好地使用它。 1733 | 1734 | ### 使用隐含规则 1735 | 1736 | 如果要使用隐含规则生成你需要的目标,你所需要做的就是不要写出这个目标的规则。那么,make会试图去自动推导产生这个目标的规则和命令,如果make可以自动推导生成这个目标的规则和命令,那么这个行为就是隐含规则的自动推导。当然,隐含规则是make事先约定好的一些东西。例如,我们有下面的一个Makefile: 1737 | ```make 1738 | foo: foo.o bar.o 1739 | cc –o foo foo.o bar.o $(CFLAGS) $(LDFLAGS) 1740 | ``` 1741 | 我们可以注意到,这个Makefile中并没有写下如何生成foo.o和bar.o这两目标的规则和命令。因为make的"隐含规则"功能会自动为我们自动去推导这两个目标的依赖目标和生成命令。 1742 | 1743 | make会在自己的"隐含规则"库中寻找可以用的规则,如果找到,那么就会使用。如果找不到,那么就会报错。在上面的那个例子中,make调用的隐含规则是,把[.o]的目标的依赖文件置成[.c],并使用C的编译命令"cc –c $(CFLAGS) [.c]"来生成[.o]的目标。也就是说,我们完全没有必要写下下面的两条规则: 1744 | ```make 1745 | foo.o: foo.c 1746 | cc –c foo.c $(CFLAGS) 1747 | bar.o: bar.c 1748 | cc –c bar.c $(CFLAGS) 1749 | ``` 1750 | 因为,这已经是"约定"好了的事了,make和我们约定好了用C编译器"cc"生成[.o]文件的规则,这就是隐含规则。 1751 | 1752 | 当然,如果我们为[.o]文件书写了自己的规则,那么make就不会自动推导并调用隐含规则,它会按照我们写好的规则忠实地执行。 1753 | 1754 | 还有,在make的"隐含规则库"中,每一条隐含规则都在库中有其顺序,越靠前的则是越被经常使用的,所以,这会导致我们有些时候即使我们显示地指定了目标依赖,make也不会管。如下面这条规则(没有命令): 1755 | ```make 1756 | foo.o: foo.p 1757 | ``` 1758 | 依赖文件"foo.p"(Pascal程序的源文件)有可能变得没有意义。如果目录下存在了"foo.c"文件,那么我们的隐含规则一样会生效,并会通过"foo.c"调用C的编译器生成foo.o文件。因为,在隐含规则中,Pascal的规则出现在C的规则之后,所以,make找到可以生成foo.o的C的规则就不再寻找下一条规则了。如果你确实不希望任何隐含规则推导,那么,你就不要只写出"依赖规则",而不写命令。 1759 | 1760 | ### 隐含规则一览 1761 | 1762 | 这里我们将讲述所有预先设置(也就是make内建)的隐含规则,如果我们不明确地写下规则,那么,make就会在这些规则中寻找所需要规则和命令。当然,我们也可以使用make的参数"-r"或"--no-builtin-rules"选项来取消所有的预设置的隐含规则。 1763 | 1764 | 当然,即使是我们指定了"-r"参数,某些隐含规则还是会生效,因为有许多的隐含规则都是使用了"后缀规则"来定义的,所以,只要隐含规则中有"后缀列表"(也就一系统定义在目标.SUFFIXES的依赖目标),那么隐含规则就会生效。默认的后缀列表是:.out, .a, .ln, .o, .c, .cc, .C, .p, .f, .F, .r, .y, .l, .s, .S, .mod, .sym, .def, .h, .info, .dvi, .tex, .texinfo, .texi, .txinfo, .w, .ch .web, .sh, .elc, .el。具体的细节,我们会在后面讲述。 1765 | 1766 | 还是先来看一看常用的隐含规则吧。 1767 | 1768 | 1. 编译C程序的隐含规则。"[n].o"的目标的依赖目标会自动推导为"[n].c",并且其生成命令是"$(CC) –c $(CPPFLAGS) $(CFLAGS)" 1769 | 1770 | 2. 编译C++程序的隐含规则。"[n].o"的目标的依赖目标会自动推导为"[n].cc"或是"[n].C",并且其生成命令是"$(CXX) –c $(CPPFLAGS) $(CFLAGS)"。(建议使用".cc"作为C++源文件的后缀,而不是".C") 1771 | 1772 | 3. 编译Pascal程序的隐含规则。"[n].o"的目标的依赖目标会自动推导为"[n].p",并且其生成命令是"$(PC) –c $(PFLAGS)"。 1773 | 1774 | 4. 编译Fortran/Ratfor程序的隐含规则。"[n].o"的目标的依赖目标会自动推导为"[n].r"或"[n].F"或"[n].f",并且其生成命令是: 1775 | ```make 1776 | ".f" "$(FC) –c $(FFLAGS)" 1777 | ".F" "$(FC) –c $(FFLAGS) $(CPPFLAGS)" 1778 | ".f" "$(FC) –c $(FFLAGS) $(RFLAGS)" 1779 | ``` 1780 | 1781 | 5. 预处理Fortran/Ratfor程序的隐含规则。"[n].f"的目标的依赖目标会自动推导为"[n].r"或"[n].F"。这个规则只是转换Ratfor或有预处理的Fortran程序到一个标准的Fortran程序。其使用的命令是: 1782 | ```make 1783 | ".F" "$(FC) –F $(CPPFLAGS) $(FFLAGS)" 1784 | ".r" "$(FC) –F $(FFLAGS) $(RFLAGS)" 1785 | ``` 1786 | 1787 | 6. 编译Modula-2程序的隐含规则。"[n].sym"的目标的依赖目标会自动推导为"[n].def",并且其生成命令是:"$(M2C) $(M2FLAGS) $(DEFFLAGS)"。"[n.o]" 的目标的依赖目标会自动推导为"[n].mod",并且其生成命令是:"$(M2C) $(M2FLAGS) $(MODFLAGS)"。 1788 | 1789 | 7. 汇编和汇编预处理的隐含规则。"[n].o" 的目标的依赖目标会自动推导为"[n].s",默认使用编译品"as",并且其生成命令是:"$(AS) $(ASFLAGS)"。"[n].s" 的目标的依赖目标会自动推导为"[n].S",默认使用C预编译器"cpp",并且其生成命令是:"$(AS) $(ASFLAGS)"。 1790 | 1791 | 8. 链接Object文件的隐含规则。"[n]"目标依赖于"[n].o",通过运行C的编译器来运行链接程序生成(一般是"ld"),其生成命令是:"$(CC) $(LDFLAGS) [n].o $(LOADLIBES) $(LDLIBS)"。这个规则对于只有一个源文件的工程有效,同时也对多个Object文件(由不同的源文件生成)的也有效。例如如下规则: 1792 | ```make 1793 | x: y.o z.o 1794 | ``` 1795 | 并且"x.c"、"y.c"和"z.c"都存在时,隐含规则将执行如下命令: 1796 | ```make 1797 | cc -c x.c -o x.o 1798 | cc -c y.c -o y.o 1799 | cc -c z.c -o z.o 1800 | cc x.o y.o z.o -o x 1801 | rm -f x.o 1802 | rm -f y.o 1803 | rm -f z.o 1804 | ``` 1805 | 如果没有一个源文件(如上例中的x.c)和你的目标名字(如上例中的x)相关联,那么,你最好写出自己的生成规则,不然,隐含规则会报错的。 1806 | 1807 | 9. Yacc C程序时的隐含规则。"[n].c"的依赖文件被自动推导为"n.y"(Yacc生成的文件),其生成命令是:"$(YACC) $(YFALGS)"。("Yacc"是一个语法分析器,关于其细节请查看相关资料) 1808 | 1809 | 10. Lex C程序时的隐含规则。"[n].c"的依赖文件被自动推导为"n.l"(Lex生成的文件),其生成命令是:"$(LEX) $(LFALGS)"。(关于"Lex"的细节请查看相关资料) 1810 | 1811 | 11. Lex Ratfor程序时的隐含规则。"[n].r"的依赖文件被自动推导为"n.l"(Lex生成的文件),其生成命令是:"$(LEX) $(LFALGS)"。 1812 | 1813 | 12. 从C程序、Yacc文件或Lex文件创建Lint库的隐含规则。"[n].ln" (lint生成的文件)的依赖文件被自动推导为"n.c",其生成命令是:"$(LINT) $(LINTFALGS) $(CPPFLAGS) -i"。对于"[n].y"和"[n].l"也是同样的规则。 1814 | 1815 | ### 隐含规则使用的变量 1816 | 1817 | 在隐含规则中的命令中,基本上都是使用了一些预先设置的变量。你可以在你的makefile中改变这些变量的值,或是在make的命令行中传入这些值,或是在你的环境变量中设置这些值,无论怎么样,只要设置了这些特定的变量,那么其就会对隐含规则起作用。当然,你也可以利用make的"-R"或"--no–builtin-variables"参数来取消你所定义的变量对隐含规则的作用。 1818 | 1819 | 例如,第一条隐含规则——编译C程序的隐含规则的命令是"$(CC) –c $(CFLAGS) $(CPPFLAGS)"。Make默认的编译命令是"cc",如果你把变量"$(CC)"重定义成"gcc",把变量"$(CFLAGS)"重定义成"-g",那么,隐含规则中的命令全部会以"gcc –c -g $(CPPFLAGS)"的样子来执行了。 1820 | 1821 | 我们可以把隐含规则中使用的变量分成两种:一种是命令相关的,如"CC";一种是参数相的关,如"CFLAGS"。下面是所有隐含规则中会用到的变量: 1822 | 1823 | 1、关于命令的变量。 1824 | 1825 | + AR 函数库打包程序。默认命令是"ar"。 1826 | + AS 汇编语言编译程序。默认命令是"as"。 1827 | + CC C语言编译程序。默认命令是"cc"。 1828 | + CXX C++语言编译程序。默认命令是"g++"。 1829 | + CO 从 RCS文件中扩展文件程序。默认命令是"co"。 1830 | + CPP C程序的预处理器(输出是标准输出设备)。默认命令是"$(CC) –E"。 1831 | + FC Fortran 和 Ratfor 的编译器和预处理程序。默认命令是"f77"。 1832 | + GET 从SCCS文件中扩展文件的程序。默认命令是"get"。 1833 | + LEX Lex方法分析器程序(针对于C或Ratfor)。默认命令是"lex"。 1834 | + PC Pascal语言编译程序。默认命令是"pc"。 1835 | + YACC Yacc文法分析器(针对于C程序)。默认命令是"yacc"。 1836 | + YACCR Yacc文法分析器(针对于Ratfor程序)。默认命令是"yacc –r"。 1837 | + MAKEINFO 转换Texinfo源文件(.texi)到Info文件程序。默认命令是"makeinfo"。 1838 | + TEX 从TeX源文件创建TeX DVI文件的程序。默认命令是"tex"。 1839 | + TEXI2DVI 从Texinfo源文件创建军TeX DVI 文件的程序。默认命令是"texi2dvi"。 1840 | + WEAVE 转换Web到TeX的程序。默认命令是"weave"。 1841 | + CWEAVE 转换C Web 到 TeX的程序。默认命令是"cweave"。 1842 | + TANGLE 转换Web到Pascal语言的程序。默认命令是"tangle"。 1843 | + CTANGLE 转换C Web 到 C。默认命令是"ctangle"。 1844 | + RM 删除文件命令。默认命令是"rm –f"。 1845 | 1846 | 2、关于命令参数的变量 1847 | 1848 | 下面的这些变量都是相关上面的命令的参数。如果没有指明其默认值,那么其默认值都是空。 1849 | 1850 | + ARFLAGS 函数库打包程序AR命令的参数。默认值是"rv"。 1851 | + ASFLAGS 汇编语言编译器参数。(当明显地调用".s"或".S"文件时)。 1852 | + CFLAGS C语言编译器参数。 1853 | + CXXFLAGS C++语言编译器参数。 1854 | + COFLAGS RCS命令参数。 1855 | + CPPFLAGS C预处理器参数。( C 和 Fortran 编译器也会用到)。 1856 | + FFLAGS Fortran语言编译器参数。 1857 | + GFLAGS SCCS "get"程序参数。 1858 | + LDFLAGS 链接器参数。(如:"ld") 1859 | + LFLAGS Lex文法分析器参数。 1860 | + PFLAGS Pascal语言编译器参数。 1861 | + RFLAGS Ratfor 程序的Fortran 编译器参数。 1862 | + YFLAGS Yacc文法分析器参数。 1863 | 1864 | ### 隐含规则链 1865 | 1866 | 有些时候,一个目标可能被一系列的隐含规则所作用。例如,一个[.o]的文件生成,可能会是先被Yacc的[.y]文件先成[.c],然后再被C的编译器生成。我们把这一系列的隐含规则叫做"隐含规则链"。 1867 | 1868 | 在上面的例子中,如果文件[.c]存在,那么就直接调用C的编译器的隐含规则,如果没有[.c]文件,但有一个[.y]文件,那么Yacc的隐含规则会被调用,生成[.c]文件,然后,再调用C编译的隐含规则最终由[.c]生成[.o]文件,达到目标。 1869 | 1870 | 我们把这种[.c]的文件(或是目标),叫做中间目标。不管怎么样,make会努力自动推导生成目标的一切方法,不管中间目标有多少,其都会执着地把所有的隐含规则和你书写的规则全部合起来分析,努力达到目标,所以,有些时候,可能会让你觉得奇怪,怎么我的目标会这样生成?怎么我的makefile发疯了? 1871 | 1872 | 在默认情况下,对于中间目标,它和一般的目标有两个地方所不同:第一个不同是除非中间的目标不存在,才会引发中间规则。第二个不同的是,只要目标成功产生,那么,产生最终目标过程中,所产生的中间目标文件会被以"rm -f"删除。 1873 | 1874 | 通常,一个被makefile指定成目标或是依赖目标的文件不能被当作中介。然而,你可以明显地说明一个文件或是目标是中介目标,你可以使用伪目标".INTERMEDIATE"来强制声明。(如:.INTERMEDIATE : mid ) 1875 | 1876 | 你也可以阻止make自动删除中间目标,要做到这一点,你可以使用伪目标".SECONDARY"来强制声明(如:.SECONDARY: sec)。你还可以把你的目标,以模式的方式来指定(如:%.o)成伪目标".PRECIOUS"的依赖目标,以保存被隐含规则所生成的中间文件。 1877 | 1878 | 在"隐含规则链"中,禁止同一个目标出现两次或两次以上,这样一来,就可防止在make自动推导时出现无限递归的情况。 1879 | 1880 | Make会优化一些特殊的隐含规则,而不生成中间文件。如,从文件"foo.c"生成目标程序"foo",按道理,make会编译生成中间文件"foo.o",然后链接成"foo",但在实际情况下,这一动作可以被一条"cc"的命令完成(cc –o foo foo.c),于是优化过的规则就不会生成中间文件。 1881 | 1882 | ### 定义模式规则 1883 | 1884 | 你可以使用模式规则来定义一个隐含规则。一个模式规则就好像一个一般的规则,只是在规则中,目标的定义需要有"%"字符。"%"的意思是表示一个或多个任意字符。在依赖目标中同样可以使用"%",只是依赖目标中的"%"的取值,取决于其目标。 1885 | 1886 | 有一点需要注意的是,"%"的展开发生在变量和函数的展开之后,变量和函数的展开发生在make载入Makefile时,而模式规则中的"%"则发生在运行时。 1887 | 1888 | 1、模式规则介绍 1889 | 1890 | 模式规则中,至少在规则的目标定义中要包含"%",否则,就是一般的规则。目标中的"%"定义表示对文件名的匹配,"%"表示长度任意的非空字符串。例如:"%.c"表示以".c"结尾的文件名(文件名的长度至少为3),而"s.%.c"则表示以"s."开头,".c"结尾的文件名(文件名的长度至少为5)。 1891 | 1892 | 如果"%"定义在目标中,那么,目标中的"%"的值决定了依赖目标中的"%"的值,也就是说,目标中的模式的"%"决定了依赖目标中"%"的样子。例如有一个模式规则如下: 1893 | ```make 1894 | %.o: %.c ; [command ......] 1895 | ``` 1896 | 其含义是,指出了怎么从所有的[.c]文件生成相应的[.o]文件的规则。如果要生成的目标是"a.o b.o",那么"%c"就是"a.c b.c"。 1897 | 1898 | 一旦依赖目标中的"%"模式被确定,那么,make会被要求去匹配当前目录下所有的文件名,一旦找到,make就会规则下的命令,所以,在模式规则中,目标可能会是多个的,如果有模式匹配出多个目标,make就会产生所有的模式目标,此时,make关心的是依赖的文件名和生成目标的命令这两件事。 1899 | 1900 | 2、模式规则示例 1901 | 1902 | 下面这个例子表示了,把所有的[.c]文件都编译成[.o]文件. 1903 | ```make 1904 | %.o: %.c 1905 | $(CC) -c $(CFLAGS) $(CPPFLAGS) $[ -o $@ 1906 | ``` 1907 | 其中,"$@"表示所有的目标的挨个值,"$["表示了所有依赖目标的挨个值。这些奇怪的变量我们叫"自动化变量",后面会详细讲述。 1908 | 1909 | 下面的这个例子中有两个目标是模式的: 1910 | ```make 1911 | %.tab.c %.tab.h: %.y 1912 | bison -d $[ 1913 | ``` 1914 | 这条规则告诉make把所有的[.y]文件都以"bison -d [n].y"执行,然后生成"[n].tab.c"和"[n].tab.h"文件。(其中,"[n]"表示一个任意字符串)。如果我们的执行程序"foo"依赖于文件"parse.tab.o"和"scan.o",并且文件"scan.o"依赖于文件"parse.tab.h",如果"parse.y"文件被更新了,那么根据上述的规则,"bison -d parse.y"就会被执行一次,于是,"parse.tab.o"和"scan.o"的依赖文件就齐了。(假设,"parse.tab.o"由"parse.tab.c"生成,和"scan.o"由"scan.c"生成,而"foo"由"parse.tab.o"和"scan.o"链接生成,而且foo和其[.o]文件的依赖关系也写好,那么,所有的目标都会得到满足) 1915 | 1916 | 3、自动化变量 1917 | 1918 | 在上述的模式规则中,目标和依赖文件都是一系例的文件,那么我们如何书写一个命令来完成从不同的依赖文件生成相应的目标?因为在每一次的对模式规则的解析时,都会是不同的目标和依赖文件。 1919 | 1920 | 自动化变量就是完成这个功能的。在前面,我们已经对自动化变量有所提涉,相信你看到这里已对它有一个感性认识了。所谓自动化变量,就是这种变量会把模式中所定义的一系列的文件自动地挨个取出,直至所有的符合模式的文件都取完了。这种自动化变量只应出现在规则的命令中。 1921 | 1922 | 下面是所有的自动化变量及其说明: 1923 | 1924 | + $@ 表示规则中的目标文件集。在模式规则中,如果有多个目标,那么,"$@"就是匹配于目标中模式定义的集合。 1925 | + $% 仅当目标是函数库文件中,表示规则中的目标成员名。例如,如果一个目标是"foo.a(bar.o)",那么,"$%"就是"bar.o","$@"就是"foo.a"。如果目标不是函数库文件(Unix下是[.a],Windows下是[.lib]),那么,其值为空。 1926 | + $[ 依赖目标中的第一个目标名字。如果依赖目标是以模式(即"%")定义的,那么"$["将是符合模式的一系列的文件集。注意,其是一个一个取出来的。 1927 | + $? 所有比目标新的依赖目标的集合。以空格分隔。 1928 | + $^ 所有的依赖目标的集合。以空格分隔。如果在依赖目标中有多个重复的,那个这个变量会去除重复的依赖目标,只保留一份。 1929 | + $+ 这个变量很像"$^",也是所有依赖目标的集合。只是它不去除重复的依赖目标。 1930 | + $* 这个变量表示目标模式中"%"及其之前的部分。如果目标是"dir/a.foo.b",并且目标的模式是"a.%.b",那么,"$*"的值就是"dir/a.foo"。这个变量对于构造有关联的文件名是比较有较。如果目标中没有模式的定义,那么"$*"也就不能被推导出,但是,如果目标文件的后缀是make所识别的,那么"$*"就是除了后缀的那一部分。例如:如果目标是"foo.c",因为".c"是make所能识别的后缀名,所以,"$*"的值就是"foo"。这个特性是GNU make的,很有可能不兼容于其它版本的make,所以,你应该尽量避免使用"$*",除非是在隐含规则或是静态模式中。如果目标中的后缀是make所不能识别的,那么"$*"就是空值。 1931 | 1932 | 当你希望只对更新过的依赖文件进行操作时,"$?"在显式规则中很有用,例如,假设有一个函数库文件叫"lib",其由其它几个object文件更新。那么把object文件打包的比较有效率的Makefile规则是: 1933 | ```make 1934 | lib: foo.o bar.o lose.o win.o 1935 | ar r lib $? 1936 | ``` 1937 | 在上述所列出来的自动量变量中。四个变量($@、$[、$%、$*)在扩展时只会有一个文件,而另三个的值是一个文件列表。这七个自动化变量还可以取得文件的目录名或是在当前目录下的符合模式的文件名,只需要搭配上"D"或"F"字样。这是GNU make中老版本的特性,在新版本中,我们使用函数"dir"或"notdir"就可以做到了。"D"的含义就是Directory,就是目录,"F"的含义就是File,就是文件。 1938 | 1939 | 下面是对于上面的七个变量分别加上"D"或是"F"的含义: 1940 | 1941 | + $(@D) 表示"$@"的目录部分(不以斜杠作为结尾),如果"$@"值是"dir/foo.o",那么"$(@D)"就是"dir",而如果"$@"中没有包含斜杠的话,其值就是"."(当前目录)。 1942 | + $(@F) 表示"$@"的文件部分,如果"$@"值是"dir/foo.o",那么"$(@F)"就是"foo.o","$(@F)"相当于函数"$(notdir $@)"。 1943 | + "$(*D)" "$(*F)" 和上面所述的同理,也是取文件的目录部分和文件部分。对于上面的那个例子,"$(*D)"返回"dir",而"$(*F)"返回"foo" 1944 | + "$(%D)" "$(%F)" 分别表示了函数包文件成员的目录部分和文件部分。这对于形同"archive(member)"形式的目标中的"member"中包含了不同的目录很有用。 1945 | + "$([D)" "$([F)" 分别表示依赖文件的目录部分和文件部分。 1946 | + "$(^D)" "$(^F)" 分别表示所有依赖文件的目录部分和文件部分。(无相同的) 1947 | + "$(+D)" "$(+F)" 分别表示所有依赖文件的目录部分和文件部分。(可以有相同的) 1948 | + "$(?D)" "$(?F)" 分别表示被更新的依赖文件的目录部分和文件部分。 1949 | 1950 | 最后想提醒一下的是,对于"$[",为了避免产生不必要的麻烦,我们最好给$后面的那个特定字符都加上圆括号,比如,"$([)"就要比"$["要好一些。 1951 | 1952 | 还得要注意的是,这些变量只使用在规则的命令中,而且一般都是"显式规则"和"静态模式规则"(参见前面"书写规则"一章)。其在隐含规则中并没有意义。 1953 | 1954 | 4、模式的匹配 1955 | 1956 | 一般来说,一个目标的模式有一个有前缀或是后缀的"%",或是没有前后缀,直接就是一个"%"。因为"%"代表一个或多个字符,所以在定义好了的模式中,我们把"%"所匹配的内容叫做"茎",例如"%.c"所匹配的文件"test.c"中"test"就是"茎"。因为在目标和依赖目标中同时有"%"时,依赖目标的"茎"会传给目标,当做目标中的"茎"。 1957 | 1958 | 当一个模式匹配包含有斜杠(实际也不经常包含)的文件时,那么在进行模式匹配时,目录部分会首先被移开,然后进行匹配,成功后,再把目录加回去。在进行"茎"的传递时,我们需要知道这个步骤。例如有一个模式"e%t",文件"src/eat"匹配于该模式,于是"src/a"就是其"茎",如果这个模式定义在依赖目标中,而被依赖于这个模式的目标中又有个模式"c%r",那么,目标就是"src/car"。("茎"被传递) 1959 | 1960 | 5、重载内建隐含规则 1961 | 1962 | 你可以重载内建的隐含规则(或是定义一个全新的),例如你可以重新构造和内建隐含规则不同的命令,如: 1963 | ```make 1964 | %.o: %.c 1965 | $(CC) -c $(CPPFLAGS) $(CFLAGS) -D$(date) 1966 | ``` 1967 | 你可以取消内建的隐含规则,只要不在后面写命令就行。如: 1968 | ```make 1969 | %.o: %.s 1970 | ``` 1971 | 同样,你也可以重新定义一个全新的隐含规则,其在隐含规则中的位置取决于你在哪里写下这个规则。朝前的位置就靠前。 1972 | 1973 | ### 老式风格的"后缀规则" 1974 | 1975 | 后缀规则是一个比较老式的定义隐含规则的方法。后缀规则会被模式规则逐步地取代。因为模式规则更强更清晰。为了和老版本的Makefile兼容,GNU make同样兼容于这些东西。后缀规则有两种方式:"双后缀"和"单后缀"。 1976 | 1977 | 双后缀规则定义了一对后缀:目标文件的后缀和依赖目标(源文件)的后缀。如".c.o"相当于"%o: %c"。单后缀规则只定义一个后缀,也就是源文件的后缀。如".c"相当于"%: %.c"。 1978 | 1979 | 后缀规则中所定义的后缀应该是make所认识的,如果一个后缀是make所认识的,那么这个规则就是单后缀规则,而如果两个连在一起的后缀都被make所认识,那就是双后缀规则。例如:".c"和".o"都是make所知道。因而,如果你定义了一个规则是".c.o"那么其就是双后缀规则,意义就是".c"是源文件的后缀,".o"是目标文件的后缀。如下示例: 1980 | ```make 1981 | .c.o: 1982 | $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@ $[ 1983 | ``` 1984 | 后缀规则不允许任何的依赖文件,如果有依赖文件的话,那就不是后缀规则,那些后缀统统被认为是文件名,如: 1985 | ```make 1986 | .c.o: foo.h 1987 | $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@ $[ 1988 | ``` 1989 | 这个例子,就是说,文件".c.o"依赖于文件"foo.h",而不是我们想要的这样: 1990 | ```make 1991 | %.o: %.c foo.h 1992 | $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@ $[ 1993 | ``` 1994 | 后缀规则中,如果没有命令,那是毫无意义的。因为他也不会移去内建的隐含规则。 1995 | 1996 | 而要让make知道一些特定的后缀,我们可以使用伪目标".SUFFIXES"来定义或是删除,如: 1997 | ```make 1998 | .SUFFIXES: .hack .win 1999 | ``` 2000 | 把后缀.hack和.win加入后缀列表中的末尾。 2001 | ```make 2002 | .SUFFIXES: # 删除默认的后缀 2003 | .SUFFIXES: .c .o .h # 定义自己的后缀 2004 | ``` 2005 | 先清楚默认后缀,后定义自己的后缀列表。 2006 | 2007 | make的参数"-r"或"-no-builtin-rules"也会使用得默认的后缀列表为空。而变量"SUFFIXE"被用来定义默认的后缀列表,你可以用".SUFFIXES"来改变后缀列表,但请不要改变变量"SUFFIXE"的值。 2008 | 2009 | ### 隐含规则搜索算法 2010 | 2011 | 比如我们有一个目标叫 T。下面是搜索目标T的规则的算法。请注意,在下面,我们没有提到后缀规则,原因是,所有的后缀规则在Makefile被载入内存时,会被转换成模式规则。如果目标是"archive(member)"的函数库文件模式,那么这个算法会被运行两次,第一次是找目标T,如果没有找到的话,那么进入第二次,第二次会把"member"当作T来搜索。 2012 | 2013 | 1、把T的目录部分分离出来。叫D,而剩余部分叫N。(如:如果T是"src/foo.o",那么,D就是"src/",N就是"foo.o") 2014 | 2015 | 2、创建所有匹配于T或是N的模式规则列表。 2016 | 2017 | 3、如果在模式规则列表中有匹配所有文件的模式,如"%",那么从列表中移除其它的模式。 2018 | 2019 | 4、移除列表中没有命令的规则。 2020 | 2021 | 5、对于第一个在列表中的模式规则: 2022 | ] 推导其"茎"S,S应该是T或是N匹配于模式中"%"非空的部分。 2023 | ] 计算依赖文件。把依赖文件中的"%"都替换成"茎"S。如果目标模式中没有包含斜框字符,而把D加在第一个依赖文件的开头。 2024 | ] 测试是否所有的依赖文件都存在或是理当存在。(如果有一个文件被定义成另外一个规则的目标文件,或者是一个显式规则的依赖文件,那么这个文件就叫"理当存在") 2025 | ] 如果所有的依赖文件存在或是理当存在,或是就没有依赖文件。那么这条规则将被采用,退出该算法。 2026 | 2027 | 6、如果经过第5步,没有模式规则被找到,那么就做更进一步的搜索。对于存在于列表中的第一个模式规则: 2028 | ] 如果规则是终止规则,那就忽略它,继续下一条模式规则。 2029 | ] 计算依赖文件。(同第5步) 2030 | ] 测试所有的依赖文件是否存在或是理当存在。 2031 | ] 对于不存在的依赖文件,递归调用这个算法查找他是否可以被隐含规则找到。 2032 | ] 如果所有的依赖文件存在或是理当存在,或是就根本没有依赖文件。那么这条规则被采用,退出该算法。 2033 | 2034 | 7、如果没有隐含规则可以使用,查看".DEFAULT"规则,如果有,采用,把".DEFAULT"的命令给T使用。 2035 | 2036 | 一旦规则被找到,就会执行其相当的命令,而此时,我们的自动化变量的值才会生成。 2037 | 2038 | 2039 | ## 使用make更新函数库文件 2040 | 2041 | 函数库文件也就是对Object文件(程序编译的中间文件)的打包文件。在Unix下,一般是由命令"ar"来完成打包工作。 2042 | 2043 | ### 函数库文件的成员 2044 | 2045 | 一个函数库文件由多个文件组成。你可以以如下格式指定函数库文件及其组成: 2046 | ```make 2047 | archive(member) 2048 | ``` 2049 | 这个不是一个命令,而一个目标和依赖的定义。一般来说,这种用法基本上就是为了"ar"命令来服务的。如: 2050 | ```make 2051 | foolib(hack.o): hack.o 2052 | ar cr foolib hack.o 2053 | ``` 2054 | 如果要指定多个member,那就以空格分开,如: 2055 | ```make 2056 | foolib(hack.o kludge.o) 2057 | ``` 2058 | 其等价于: 2059 | ```make 2060 | foolib(hack.o) foolib(kludge.o) 2061 | ``` 2062 | 你还可以使用Shell的文件通配符来定义,如: 2063 | ```make 2064 | foolib(*.o) 2065 | ``` 2066 | 2067 | ### 函数库成员的隐含规则 2068 | 2069 | 当make搜索一个目标的隐含规则时,一个特殊的特性是,如果这个目标是"a(m)"形式的,其会把目标变成"(m)"。于是,如果我们的成员是"%.o"的模式定义,并且如果我们使用"make foo.a(bar.o)"的形式调用Makefile时,隐含规则会去找"bar.o"的规则,如果没有定义bar.o的规则,那么内建隐含规则生效,make会去找bar.c文件来生成bar.o,如果找得到的话,make执行的命令大致如下: 2070 | ```make 2071 | cc -c bar.c -o bar.o 2072 | ar r foo.a bar.o 2073 | rm -f bar.o 2074 | ``` 2075 | 还有一个变量要注意的是"$%",这是专属函数库文件的自动化变量,有关其说明请参见"自动化变量"一节。 2076 | 2077 | ### 函数库文件的后缀规则 2078 | 2079 | 你可以使用"后缀规则"和"隐含规则"来生成函数库打包文件,如: 2080 | ```make 2081 | .c.a: 2082 | $(CC) $(CFLAGS) $(CPPFLAGS) -c $[ -o $*.o 2083 | $(AR) r $@ $*.o 2084 | $(RM) $*.o 2085 | ``` 2086 | 其等效于: 2087 | ```make 2088 | (%.o): %.c 2089 | $(CC) $(CFLAGS) $(CPPFLAGS) -c $[ -o $*.o 2090 | $(AR) r $@ $*.o 2091 | $(RM) $*.o 2092 | ``` 2093 | 2094 | ### 注意事项 2095 | 2096 | 在进行函数库打包文件生成时,请小心使用make的并行机制("-j"参数)。如果多个ar命令在同一时间运行在同一个函数库打包文件上,就很有可以损坏这个函数库文件。所以,在make未来的版本中,应该提供一种机制来避免并行操作发生在函数打包文件上。 2097 | 2098 | 但就目前而言,你还是应该不要尽量不要使用"-j"参数。 2099 | 2100 | 2101 | ## 后序 2102 | 2103 | 终于到写结束语的时候了,以上基本上就是GNU make的Makefile的所有细节了。其它的产商的make基本上也就是这样的,无论什么样的make,都是以文件的依赖性为基础的,其基本是都是遵循一个标准的。这篇文档中80%的技术细节都适用于任何的make,我猜测"函数"那一章的内容可能不是其它make所支持的,而隐含规则方面,我想不同的make会有不同的实现,我没有精力来查看GNU的make和VC的nmake、BCB的make,或是别的UNIX下的make有些什么样的差别,一是时间精力不够,二是因为我基本上都是在Unix下使用make,以前在SCO Unix和IBM的AIX,现在在Linux、Solaris、HP-UX、AIX和Alpha下使用,Linux和Solaris下更多一点。不过,我可以肯定的是,在Unix下的make,无论是哪种平台,几乎都使用了Richard Stallman开发的make和cc/gcc的编译器,而且,基本上都是GNU的make(公司里所有的UNIX机器上都被装上了GNU的东西,所以,使用GNU的程序也就多了一些)。GNU的东西还是很不错的,特别是使用得深了以后,越来越觉得GNU的软件的强大,也越来越觉得GNU的在操作系统中(主要是Unix,甚至Windows)"杀伤力"。 2104 | 2105 | 对于上述所有的make的细节,我们不但可以利用make这个工具来编译我们的程序,还可以利用make来完成其它的工作,因为规则中的命令可以是任何Shell之下的命令,所以,在Unix下,你不一定只是使用程序语言的编译器,你还可以在Makefile中书写其它的命令,如:tar、awk、mail、sed、cvs、compress、ls、rm、yacc、rpm、ftp……等等,等等,来完成诸如"程序打包"、"程序备份"、"制作程序安装包"、"提交代码"、"使用程序模板"、"合并文件"等等五花八门的功能,文件操作,文件管理,编程开发设计,或是其它一些异想天开的东西。比如,以前在书写银行交易程序时,由于银行的交易程序基本一样,就见到有人书写了一些交易的通用程序模板,在该模板中把一些网络通讯、数据库操作的、业务操作共性的东西写在一个文件中,在这些文件中用些诸如"@@@N、###N"奇怪字串标注一些位置,然后书写交易时,只需按照一种特定的规则书写特定的处理,最后在make时,使用awk和sed,把模板中的"@@@N、###N"等字串替代成特定的程序,形成C文件,然后再编译。这个动作很像数据库的"扩展C"语言(即在C语言中用"EXEC SQL"的样子执行SQL语句,在用cc/gcc编译之前,需要使用"扩展C"的翻译程序,如cpre,把其翻译成标准C)。如果你在使用make时有一些更为绝妙的方法,请记得告诉我啊。 2106 | 2107 | 回头看看整篇文档,不觉记起几年前刚刚开始在Unix下做开发的时候,有人问我会不会写Makefile时,我两眼发直,根本不知道在说什么。一开始看到别人在vi中写完程序后输入"!make"时,还以为是vi的功能,后来才知道有一个Makefile在作怪,于是上网查啊查,那时又不愿意看英文,发现就根本没有中文的文档介绍Makefile,只得看别人写的Makefile,自己瞎碰瞎搞才积累了一点知识,但在很多地方完全是知其然不知所以然。后来开始从事UNIX下产品软件的开发,看到一个400人年,近200万行代码的大工程,发现要编译这样一个庞然大物,如果没有Makefile,那会是多么恐怖的一样事啊。于是横下心来,狠命地读了一堆英文文档,才觉得对其掌握了。但发现目前网上对Makefile介绍的文章还是少得那么的可怜,所以想写这样一篇文章,共享给大家,希望能对各位有所帮助。 2108 | 2109 | 现在我终于写完了,看了看文件的创建时间,这篇技术文档也写了两个多月了。发现,自己知道是一回事,要写下来,跟别人讲述又是另外一回事,而且,现在越来越没有时间专研技术细节,所以在写作时,发现在阐述一些细节问题时很难做到严谨和精练,而且对先讲什么后讲什么不是很清楚,所以,还是参考了一些国外站点上的资料和题纲,以及一些技术书籍的语言风格,才得以完成。整篇文档的提纲是基于GNU的Makefile技术手册的提纲来书写的,并结合了自己的工作经验,以及自己的学习历程。因为从来没有写过这么长,这么细的文档,所以一定会有很多地方存在表达问题,语言歧义或是错误。因些,我迫切地得等待各位给我指证和建议,以及任何的反馈。 2110 | 2111 | links 2112 | ----- 2113 | + [目录](../clang) 2114 | -------------------------------------------------------------------------------- /clang/README.md: -------------------------------------------------------------------------------- 1 | Index 2 | ----- 3 | 4 | ####How to Write Makefile 5 | *2013-01-28* 6 | 转载自[陈皓的Blog](http://blog.csdn.net/haoel/article/details/2886)...[Read More](clang/How-to-Write-Makefile.md) 7 | 8 | -------------------------------------------------------------------------------- /clang/upload.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "flag" 7 | "fmt" 8 | "github.com/xing4git/cmdutils" 9 | "io/ioutil" 10 | "os" 11 | "regexp" 12 | "sort" 13 | ) 14 | 15 | var ( 16 | readme = bytes.NewBuffer(make([]byte, 0)) 17 | change = bytes.NewBuffer(make([]byte, 0)) 18 | commit = bytes.NewBuffer(make([]byte, 0)) 19 | ) 20 | 21 | var ( 22 | reg = regexp.MustCompile("^_\\d{4}-\\d{2}-\\d{2}-") 23 | filenames = make([]string, 0) 24 | dirname = flag.String("d", "golang", "current dir name") 25 | ) 26 | 27 | func init() { 28 | flag.Parse() 29 | flag.PrintDefaults() 30 | fmt.Println("current dir name: " + *dirname) 31 | } 32 | 33 | func main() { 34 | dir, err := os.Open(".") 35 | checkErr(err) 36 | defer dir.Close() 37 | 38 | fis, err := dir.Readdir(0) 39 | checkErr(err) 40 | 41 | for i := 0; i < len(fis); i++ { 42 | fi := fis[i] 43 | filename := fi.Name() 44 | if reg.Match([]byte(filename)) { 45 | filenames = append(filenames, filename) 46 | } 47 | } 48 | 49 | sort.Strings(filenames) 50 | fmt.Println("filenames: ", filenames, "\n") 51 | 52 | readme.WriteString("Index\n") 53 | readme.WriteString("-----\n\n") 54 | change.WriteString("update README.md;") 55 | 56 | for key, value := range filenames { 57 | realname := value[12:] 58 | readme.WriteString("####" + decorateFilename(realname) + "\n") 59 | 60 | file, err := os.Open(value) 61 | checkErr(err) 62 | defer file.Close() 63 | 64 | readme.WriteString("*" + value[1:11] + "*\n") 65 | buf := bufio.NewReader(file) 66 | line, err := buf.ReadString('\n') 67 | checkErr(err) 68 | readme.WriteString(string(line[0 : len(line)-1])) 69 | line, err = buf.ReadString('\n') 70 | checkErr(err) 71 | readme.WriteString(string(line[0 : len(line)-1])) 72 | readme.WriteString("...[Read More](" + *dirname + "/" + realname + ")\n\n") 73 | 74 | file.Seek(0, os.SEEK_SET) 75 | nbytes, err := ioutil.ReadAll(file) 76 | checkErr(err) 77 | var tempbuf []byte 78 | tempbuf = append(tempbuf, []byte(decorateFilename(realname)+"\n"+"----\n\n")...) 79 | nbytes = append(tempbuf, nbytes...) 80 | 81 | nbytes = append(nbytes, []byte("\n\n"+"links\n"+"-----\n")...) 82 | nbytes = append(nbytes, []byte("+ [目录](../"+*dirname+")\n")...) 83 | if key != 0 { 84 | previous := filenames[key-1][12:] 85 | nbytes = append(nbytes, []byte("+ 上一节: ["+decorateFilename(previous)+"]("+previous+")\n")...) 86 | } 87 | if key != len(filenames)-1 { 88 | next := filenames[key+1][12:] 89 | nbytes = append(nbytes, []byte("+ 下一节: ["+decorateFilename(next)+"]("+next+")\n")...) 90 | } 91 | 92 | pbytes, err := ioutil.ReadFile(realname) 93 | if err == nil && bytes.Equal(pbytes, nbytes) { 94 | fmt.Println("no change file:", realname) 95 | continue 96 | } 97 | 98 | change.WriteString("update " + realname + ";") 99 | err = ioutil.WriteFile(realname, nbytes, 0664) 100 | checkErr(err) 101 | } 102 | 103 | err = ioutil.WriteFile("README.md", readme.Bytes(), 0664) 104 | checkErr(err) 105 | 106 | commit.WriteString("git add .\n") 107 | commit.WriteString("git commit -a -m '" + change.String() + "'\n") 108 | commit.WriteString("git push -u origin master\n") 109 | fmt.Println(commit.String()) 110 | ret, err := cmdutils.BashExecute(commit.String()) 111 | checkErr(err) 112 | fmt.Println(ret) 113 | } 114 | 115 | func decorateFilename(str string) string { 116 | bytes := []byte(str) 117 | var suffixStart int = -1 118 | for i := len(str) - 1; i >= 0; i-- { 119 | if bytes[i] == '.' { 120 | suffixStart = i 121 | break 122 | } 123 | } 124 | 125 | if suffixStart != -1 { 126 | bytes = bytes[:suffixStart] 127 | } 128 | 129 | for pos, v := range bytes { 130 | if v == '-' { 131 | bytes[pos] = ' ' 132 | } 133 | } 134 | 135 | return string(bytes) 136 | } 137 | 138 | func checkErr(err error) { 139 | if err != nil { 140 | fmt.Fprintf(os.Stderr, "error: %s\n", err.Error()) 141 | os.Exit(1) 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /golang/Pkg-bufio.md: -------------------------------------------------------------------------------- 1 | Pkg bufio 2 | ---- 3 | 4 | bufio包提供了带有缓冲功能的Reader和Writer, 应用了`装饰者模式`. 5 | bufio.Reader是对io.Reader的包装, 并且实现了io.Reader接口. 6 | 类似的, bufio.Writer是对io.Writer的包装, 并且实现了io.Writer接口. 7 | 8 | 9 | Reader 10 | ------ 11 | bufio.Reader的定义如下: 12 | ```go 13 | type Reader struct { 14 | // 缓冲区 15 | buf []byte 16 | // 底层Reader 17 | rd io.Reader 18 | // buffer中有效数据的边界 19 | r, w int 20 | // read过程中出现的error 21 | err error 22 | lastByte int 23 | lastRuneSize int 24 | } 25 | ``` 26 | lastByte和lastRuneSize字段是为了支持unread操作而存在的. 27 | lastByte表示读取的最后一个字节数据, -1表示不可用状态. 注意lastByte的类型为int, 如果lastByte的类型为byte, -1是合法的字节数据值, 无法使用-1表示不可用状态. 将lastByte的类型设定为int则可以规避这个问题, byte强转为int之后, 取值范围是[0-255], 此时-1不再是合法值, 因此可以用来表示不可用状态. 28 | 29 | ### 创建*Reader对象 30 | 可以通过以下2个function创建*bufio.Reader对象: 31 | ```go 32 | // 指定缓冲区大小 33 | func NewReaderSize(rd io.Reader, size int) *Reader 34 | // 使用默认缓冲区大小, 相当于调用NewReaderSize(rd, defaultBufSize) 35 | func NewReader(rd io.Reader) *Reader 36 | ``` 37 | 有趣的是, 在NewReaderSize中, 会判断rd是否已经是一个*bufio.Reader对象了: 38 | ```go 39 | b, ok := rd.(*Reader) 40 | if ok && len(b.buf) >= size { 41 | return b 42 | } 43 | ``` 44 | 如果rd已经是一个*bufio.Reader对象了, 且缓冲区大小也满足条件, 则直接返回rd自身, 以防止不必要的包装. 45 | 46 | ### Read 47 | ```go 48 | func (b *Reader) Read(p []byte) (n int, err error) 49 | ``` 50 | *bufio.Reader实现了io.Reader接口, 就是因为*bufio.Reader具有Read方法. 51 | 如果缓冲区中没有数据: 52 | ```go 53 | if b.w == b.r { 54 | if b.err != nil { 55 | return 0, b.readErr() 56 | } 57 | if len(p) >= len(b.buf) { 58 | // 读取数据量超过缓冲区大小时, 直接从底层的io.Reader对象读取并返回数据, 避免[]byte的copy 59 | // 注意, 这部分数据是没有进入缓冲区的 60 | n, b.err = b.rd.Read(p) 61 | if n > 0 { 62 | b.lastByte = int(p[n-1]) 63 | b.lastRuneSize = -1 64 | } 65 | return n, b.readErr() 66 | } 67 | // 试图填满缓冲区 68 | b.fill() 69 | // 此时如果缓冲区仍然没有数据, 则说明肯定出现了error 70 | if b.w == b.r { 71 | return 0, b.readErr() 72 | } 73 | } 74 | ``` 75 | 接下来, 返回缓冲区中的数据: 76 | ```go 77 | // 最多从缓冲区中取出n个字节 78 | if n > b.w-b.r { 79 | n = b.w - b.r 80 | } 81 | copy(p[0:n], b.buf[b.r:]) 82 | // 改变标记字段 83 | b.r += n 84 | b.lastByte = int(b.buf[b.r-1]) 85 | b.lastRuneSize = -1 86 | return n, nil 87 | ``` 88 | 从代码可以看出, Read最多调用一次底层Reader的Read方法, 因此返回的n是有可能小于len(p)的. 89 | 90 | ### Buffered 91 | 返回当前缓冲区中的有效字节数. 92 | ```go 93 | func (b *Reader) Buffered() int { return b.w - b.r } 94 | ``` 95 | 96 | ### ReadSlice 97 | ```go 98 | func (b *Reader) ReadSlice(delim byte) (line []byte, err error) 99 | ``` 100 | 读取并返回byte数据, 直到读取到指定的delim, 或者发生error, 或者缓冲区已满. 101 | 如果缓冲区中的数据满足条件, 则直接返回: 102 | ```go 103 | if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 { 104 | line1 := b.buf[b.r : b.r+i+1] 105 | b.r += i + 1 106 | return line1, nil 107 | } 108 | ``` 109 | 否则, 将数据读取到缓冲区后再进行判断: 110 | ```go 111 | for { 112 | if b.err != nil { 113 | line := b.buf[b.r:b.w] 114 | b.r = b.w 115 | return line, b.readErr() 116 | } 117 | 118 | // 记录当前缓冲区中的字节数 119 | n := b.Buffered() 120 | b.fill() 121 | 122 | // 在新读取的数据中搜索 123 | if i := bytes.IndexByte(b.buf[n:b.w], delim); i >= 0 { 124 | line := b.buf[0 : n+i+1] 125 | b.r = n + i + 1 126 | return line, nil 127 | } 128 | 129 | // 判断缓冲区是否已满 130 | if b.Buffered() >= len(b.buf) { 131 | b.r = b.w 132 | return b.buf, ErrBufferFull 133 | } 134 | } 135 | ``` 136 | 137 | ### ReadLine 138 | ```go 139 | func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) 140 | ``` 141 | 读取一行数据, 如果某行太长(超过缓冲区大小), 先返回开头部分, 并设置isPrefix为true, 其余部分将在随后的ReadLine中返回. 142 | 先调用ReadSlice得到初步数据: 143 | ```go 144 | line, err = b.ReadSlice('\n') 145 | ``` 146 | 如果err是ErrBufferFull(缓冲区已满), 处理数据后返回给调用者: 147 | ```go 148 | if err == ErrBufferFull { 149 | // 处理\r\n的情形 150 | if len(line) > 0 && line[len(line)-1] == '\r' { 151 | if b.r == 0 { 152 | // should be unreachable 153 | panic("bufio: tried to rewind past start of buffer") 154 | } 155 | // 将\r放回缓冲区, 并将其从line中删除, 以便下次调用ReadLine时一并处理'\r\n' 156 | b.r-- 157 | line = line[:len(line)-1] 158 | } 159 | // 返回的isPrefix为true, 表明该行太长, line只是该行的一部分数据 160 | return line, true, nil 161 | } 162 | ``` 163 | 如果line的最后一个字节确实是'\n', 则将'\n'或者'\r\n'从line中删除后返回: 164 | ```go 165 | if line[len(line)-1] == '\n' { 166 | drop := 1 167 | if len(line) > 1 && line[len(line)-2] == '\r' { 168 | drop = 2 169 | } 170 | line = line[:len(line)-drop] 171 | } 172 | ``` 173 | 174 | ### ReadBytes 175 | ```go 176 | func (b *Reader) ReadBytes(delim byte) (line []byte, err error) 177 | ``` 178 | ReadBytes和ReadSlice的区别在于, ReadBytes不会因为缓冲区已满就停止搜索, 而是继续下去, 直到读取到指定的delim, 或者发生了error(通常是io.EOF). 179 | ```go 180 | var frag []byte 181 | var full [][]byte 182 | err = nil 183 | 184 | for { 185 | var e error 186 | frag, e = b.ReadSlice(delim) 187 | if e == nil { // 读取到指定的delim 188 | break 189 | } 190 | if e != ErrBufferFull { // 发生了ErrBufferFull之外的error 191 | err = e 192 | break 193 | } 194 | 195 | // 处理err为ErrBufferFull的情形 196 | // 将frag中的数据copy一份, 保存在full中. 197 | buf := make([]byte, len(frag)) 198 | copy(buf, frag) 199 | full = append(full, buf) 200 | } 201 | ``` 202 | 如此以来, 数据就存储在full和frag中了, 接下来需要将2者中存储的数据合并到一个buffer中: 203 | ```go 204 | // 计算buf所需的length 205 | n := 0 206 | for i := range full { 207 | n += len(full[i]) 208 | } 209 | n += len(frag) 210 | 211 | // 将数据从full和frag中copy到buf中, 注意copy的顺序 212 | buf := make([]byte, n) 213 | n = 0 214 | for i := range full { 215 | n += copy(buf[n:], full[i]) 216 | } 217 | copy(buf[n:], frag) 218 | return buf, err 219 | ``` 220 | 221 | ### ReadString 222 | ReadString和ReadBytes类似, 区别在于ReadString返回的是string: 223 | ```go 224 | func (b *Reader) ReadString(delim byte) (line string, err error) { 225 | bytes, e := b.ReadBytes(delim) 226 | return string(bytes), e 227 | } 228 | ``` 229 | 可以调用ReadString('\n')代替ReadLine, 此时不需要处理烦人的isPrefix标记, 因为对于ReadString('\n')来说, 不管行有多长, 都只会一次性返回. 230 | 231 | 232 | Writer 233 | ---- 234 | bufio.Writer的定义如下: 235 | ```go 236 | type Writer struct { 237 | err error 238 | // 缓冲区 239 | buf []byte 240 | // buf中有效数据个数 241 | n int 242 | // 底层Writer 243 | wr io.Writer 244 | } 245 | ``` 246 | 247 | ### 创建*Writer对象 248 | 可以通过以下2个function创建*bufio.Writer对象: 249 | ```go 250 | // 指定缓冲区大小 251 | func NewWriterSize(wr io.Writer, size int) *Writer 252 | // 使用默认缓冲区大小, 相当于调用NewWriterSize(wr, defaultBufSize) 253 | func NewWriter(wr io.Writer) *Writer 254 | ``` 255 | 256 | ### Flush 257 | 将缓冲区中的数据写入相应的底层io.Writer: 258 | ```go 259 | func (b *Writer) Flush() error { 260 | if b.err != nil { 261 | return b.err 262 | } 263 | // 缓冲区中没有数据 264 | if b.n == 0 { 265 | return nil 266 | } 267 | // 将缓冲区中的数据写入io.Writer 268 | n, e := b.wr.Write(b.buf[0:b.n]) 269 | if n < b.n && e == nil { 270 | e = io.ErrShortWrite 271 | } 272 | if e != nil { 273 | // 写入了n个字节时, 将写入的部分从缓冲区中删除 274 | if n > 0 && n < b.n { 275 | copy(b.buf[0:b.n-n], b.buf[n:b.n]) 276 | } 277 | // 设置相关标记 278 | b.n -= n 279 | b.err = e 280 | return e 281 | } 282 | // 清空缓冲区 283 | b.n = 0 284 | return nil 285 | } 286 | ``` 287 | 288 | ### Available 289 | 返回缓冲区中的空闲字节数: 290 | ```go 291 | func (b *Writer) Available() int { return len(b.buf) - b.n } 292 | ``` 293 | 294 | ### Buffered 295 | 返回缓冲区中的有效字节数: 296 | ```go 297 | func (b *Writer) Buffered() int { return b.n } 298 | ``` 299 | 300 | ### Write 301 | *bufio.Writer具有Write方法, 因此*bufio.Writer实现了io.Writer接口. 302 | ```go 303 | func (b *Writer) Write(p []byte) (nn int, err error) { 304 | for len(p) > b.Available() && b.err == nil { 305 | var n int 306 | if b.Buffered() == 0 { 307 | // 需要写入大量数据, 且缓冲区中没有有效数据时, 直接将p写入底层io.Writer中 308 | n, b.err = b.wr.Write(p) 309 | } else { 310 | // 先将部分数据(b.Available()个字节)写入缓冲区中, 然后再刷新缓存 311 | n = copy(b.buf[b.n:], p) 312 | b.n += n 313 | // Flush时如果出错, 会将error存储在b.err中 314 | b.Flush() 315 | } 316 | nn += n 317 | // 截去已写入的部分 318 | p = p[n:] 319 | } 320 | if b.err != nil { 321 | return nn, b.err 322 | } 323 | // 将剩余部分写入缓冲区, 此时len(p) <= b.Available(), 即缓冲区肯定能够容纳p中的数据 324 | n := copy(b.buf[b.n:], p) 325 | b.n += n 326 | nn += n 327 | return nn, nil 328 | } 329 | ``` 330 | 331 | ### WriteByte 332 | 写入单个字节数据. 333 | ```go 334 | func (b *Writer) WriteByte(c byte) error { 335 | if b.err != nil { 336 | return b.err 337 | } 338 | // 缓冲区中没有可用空间时, 尝试执行Flush操作, 如果Flush失败, 直接返回错误 339 | if b.Available() <= 0 && b.Flush() != nil { 340 | return b.err 341 | } 342 | // 将c写入缓冲区 343 | b.buf[b.n] = c 344 | b.n++ 345 | return nil 346 | } 347 | ``` 348 | 349 | ### WriteString 350 | 写入string数据. 从源码可以看出, 相当于调用了`Write([]byte(s))`. 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | links 360 | ----- 361 | + [目录](../golang) 362 | + 下一节: [Pkg ioutil](Pkg-ioutil.md) 363 | -------------------------------------------------------------------------------- /golang/Pkg-bytes.md: -------------------------------------------------------------------------------- 1 | Pkg bytes 2 | ---- 3 | 4 | Package bytes实现了一系列操作byte slice的方法. 5 | 6 | ### Compare 7 | 比较byte slice a和b, 如果`a == b`返回0, `a < b`返回-1, `a > b`返回1. 8 | ```go 9 | func Compare(a, b []byte) int { 10 | // m取len(a)和len(b)的较小者 11 | m := len(a) 12 | if m > len(b) { 13 | m = len(b) 14 | } 15 | 16 | // 比较[0, m]之间的byte值 17 | for i, ac := range a[0:m] { 18 | bc := b[i] 19 | switch { 20 | case ac > bc: 21 | return 1 22 | case ac < bc: 23 | return -1 24 | } 25 | } 26 | 27 | // 如果[0, m]之间的byte值都相等, 则判断长度 28 | switch { 29 | case len(a) < len(b): 30 | return -1 31 | case len(a) > len(b): 32 | return 1 33 | } 34 | 35 | // [0,m]之间的byte值都相等, 且a和b的长度也相等, 因此a == b 36 | return 0 37 | } 38 | ``` 39 | 40 | ### Equal 41 | 判断2个byte slice是否相等. 此方法不是由Go语言实现的. 42 | 43 | ### Count 44 | 计算s中sep出现的次数. 45 | ```go 46 | func Count(s, sep []byte) int { 47 | n := len(sep) 48 | 49 | // n == 0 和 n > len(s) 这2种情况单独考虑, 直接返回结果 50 | if n == 0 { 51 | return utf8.RuneCount(s) + 1 52 | } 53 | if n > len(s) { 54 | return 0 55 | } 56 | 57 | count := 0 58 | c := sep[0] 59 | i := 0 60 | t := s[:len(s)-n+1] 61 | for i < len(t) { 62 | if t[i] != c { 63 | o := IndexByte(t[i:], c) 64 | // o < 0 时, 说明t[i:]不包含c, 即t[i:]中不可能包含sep了, 所以跳出循环 65 | if o < 0 { 66 | break 67 | } 68 | // i += o后, t[i] == c 69 | i += o 70 | } 71 | 72 | // 此时t[i] == c, 所以只要n == 1 或 Equal(s[i:i+n], sep) == true 都说明有新的sep出现 73 | if n == 1 || Equal(s[i:i+n], sep) { 74 | count++ 75 | // 这n个字节相等, 下次从i+n处开始判断 76 | i += n 77 | continue 78 | } 79 | 80 | // 从下个字节开始判断 81 | i++ 82 | } 83 | 84 | return count 85 | } 86 | ``` 87 | 88 | ### Index 89 | s中首次出现sep序列的索引, -1表示s中不包含sep. 90 | ```go 91 | func Index(s, sep []byte) int { 92 | n := len(sep) 93 | if n == 0 { 94 | return 0 95 | } 96 | if n > len(s) { 97 | return -1 98 | } 99 | 100 | // sep只包含一个byte时, 直接调用IndexByte即可 101 | c := sep[0] 102 | if n == 1 { 103 | return IndexByte(s, c) 104 | } 105 | 106 | // 这部分代码与Count中类似 107 | i := 0 108 | t := s[:len(s)-n+1] 109 | for i < len(t) { 110 | if t[i] != c { 111 | o := IndexByte(t[i:], c) 112 | if o < 0 { 113 | break 114 | } 115 | i += o 116 | } 117 | if Equal(s[i:i+n], sep) { 118 | return i 119 | } 120 | i++ 121 | } 122 | 123 | return -1 124 | } 125 | ``` 126 | 127 | ### LastIndex 128 | s中最后出现sep序列的索引, -1同样表示s中不包含sep. 129 | ```go 130 | func LastIndex(s, sep []byte) int { 131 | n := len(sep) 132 | if n == 0 { 133 | return len(s) 134 | } 135 | 136 | // 这里的代码比Index中的代码更容易理解 137 | c := sep[0] 138 | for i := len(s) - n; i >= 0; i-- { 139 | if s[i] == c && (n == 1 || Equal(s[i:i+n], sep)) { 140 | return i 141 | } 142 | } 143 | 144 | return -1 145 | } 146 | ``` 147 | 148 | 149 | ### Contains 150 | 判断b中是否包含指定的subslice. 151 | ```go 152 | func Contains(b, subslice []byte) bool { 153 | return Index(b, subslice) != -1 154 | } 155 | ``` 156 | 157 | ### IndexRune 158 | 将s当做utf8编码的unicode字符序列, 返回r在s中的索引. 159 | ```go 160 | func IndexRune(s []byte, r rune) int { 161 | for i := 0; i < len(s); { 162 | // 返回s[i:]中的第一个rune, size为该rune所占的字节数 163 | r1, size := utf8.DecodeRune(s[i:]) 164 | if r == r1 { 165 | return i 166 | } 167 | i += size 168 | } 169 | return -1 170 | } 171 | ``` 172 | 173 | ### IndexAny 174 | chars中任意一个字符在s中首次出现的索引. 175 | ```go 176 | func IndexAny(s []byte, chars string) int { 177 | if len(chars) > 0 { 178 | var r rune 179 | var width int 180 | 181 | for i := 0; i < len(s); i += width { 182 | // r为s[i:]中的第一个rune, width为该rune所占的字节数 183 | r = rune(s[i]) 184 | if r < utf8.RuneSelf { 185 | width = 1 186 | } else { 187 | r, width = utf8.DecodeRune(s[i:]) 188 | } 189 | 190 | // 如果r是chars其中一员, 直接返回 191 | for _, ch := range chars { 192 | if r == ch { 193 | return i 194 | } 195 | } 196 | } 197 | } 198 | return -1 199 | } 200 | ``` 201 | 202 | ### LastIndexAny 203 | chars中任意一个字符在s中最后出现的索引. 204 | ```go 205 | func LastIndexAny(s []byte, chars string) int { 206 | if len(chars) > 0 { 207 | for i := len(s); i > 0; { 208 | r, size := utf8.DecodeLastRune(s[0:i]) 209 | i -= size 210 | for _, ch := range chars { 211 | if r == ch { 212 | return i 213 | } 214 | } 215 | } 216 | } 217 | return -1 218 | } 219 | ``` 220 | 221 | ### Split 222 | bytes包中包含多个Split函数: SplitN, SplitAfterN, Split, SplitAfter等. 这些函数都是对genSplit的包装. 223 | ```go 224 | // 将s以sep分割. sepSave表示子byte数组中包含多少个sep中的字节数. 225 | // n表示最多包含多少个子byte数组: 226 | // n > 0 取n个子byte数组, n == 0 返回nil, n < 0 时返回所有子byte数组 227 | func genSplit(s, sep []byte, sepSave, n int) [][]byte { 228 | // 根据n的值确定要返回多少个byte数组 229 | if n == 0 { 230 | return nil 231 | } 232 | if len(sep) == 0 { 233 | return explode(s, n) 234 | } 235 | if n < 0 { 236 | n = Count(s, sep) + 1 237 | } 238 | 239 | c := sep[0] 240 | start := 0 241 | a := make([][]byte, n) 242 | na := 0 243 | for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ { 244 | if s[i] == c && (len(sep) == 1 || Equal(s[i:i+len(sep)], sep)) { 245 | // 找到其中一个, 从中可以看出sepSave的作用 246 | a[na] = s[start : i+sepSave] 247 | na++ 248 | start = i + len(sep) 249 | i += len(sep) - 1 250 | } 251 | } 252 | // 剩余的数据都归类到最后一个子byte数组 253 | a[na] = s[start:] 254 | 255 | return a[0 : na+1] 256 | } 257 | 258 | // 将s以sep作为分界点分割为最多n个子byte数组, 每个子byte不数组包含sep 259 | func SplitN(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) } 260 | 261 | // 将s以sep作为分界点分割为最多n个子byte数组, 每个子byte数组包含sep 262 | func SplitAfterN(s, sep []byte, n int) [][]byte { 263 | return genSplit(s, sep, len(sep), n) 264 | } 265 | 266 | // 将s以sep作为分界点分割为若干个子byte数组, 不限制子byte数组的个数. 每个子byte不数组包含sep 267 | func Split(s, sep []byte) [][]byte { return genSplit(s, sep, 0, -1) } 268 | 269 | // 将s以sep作为分界点分割为若干个子byte数组, 不限制子byte数组的个数. 每个子byte数组包含sep 270 | func SplitAfter(s, sep []byte) [][]byte { 271 | return genSplit(s, sep, len(sep), -1) 272 | } 273 | ``` 274 | 275 | ### Fields 276 | 将s以空白字符作为分界点分割为若干个子byte数组. 277 | ```go 278 | func Fields(s []byte) [][]byte { 279 | return FieldsFunc(s, unicode.IsSpace) 280 | } 281 | 282 | // 对于s中的每个rune, 都调用f函数. 如果f函数返回true, 则将其作为分界点. 283 | func FieldsFunc(s []byte, f func(rune) bool) [][]byte { 284 | // 计算得到子byte数组的长度 285 | n := 0 286 | inField := false 287 | for i := 0; i < len(s); { 288 | r, size := utf8.DecodeRune(s[i:]) 289 | wasInField := inField 290 | inField = !f(r) 291 | if inField && !wasInField { 292 | n++ 293 | } 294 | i += size 295 | } 296 | 297 | a := make([][]byte, n) 298 | na := 0 299 | fieldStart := -1 300 | for i := 0; i <= len(s) && na < n; { 301 | r, size := utf8.DecodeRune(s[i:]) 302 | if fieldStart < 0 && size > 0 && !f(r) { 303 | fieldStart = i 304 | i += size 305 | continue 306 | } 307 | if fieldStart >= 0 && (size == 0 || f(r)) { 308 | a[na] = s[fieldStart:i] 309 | na++ 310 | fieldStart = -1 311 | } 312 | if size == 0 { 313 | break 314 | } 315 | i += size 316 | } 317 | return a[0:na] 318 | } 319 | ``` 320 | 321 | ### Join 322 | 将a的每一个item通过sep连接在一起, 形成一个大的byte数组. 323 | ```go 324 | func Join(a [][]byte, sep []byte) []byte { 325 | // 处理特殊情况 326 | if len(a) == 0 { 327 | return []byte{} 328 | } 329 | if len(a) == 1 { 330 | return a[0] 331 | } 332 | 333 | // 计算返回结果的len 334 | n := len(sep) * (len(a) - 1) 335 | for i := 0; i < len(a); i++ { 336 | n += len(a[i]) 337 | } 338 | 339 | // copy 340 | b := make([]byte, n) 341 | bp := copy(b, a[0]) 342 | for _, s := range a[1:] { 343 | bp += copy(b[bp:], sep) 344 | bp += copy(b[bp:], s) 345 | } 346 | 347 | return b 348 | } 349 | ``` 350 | 351 | ### HasPrefix, HasSuffix 352 | 代码很简单. 353 | ```go 354 | // 是否以prefix开端 355 | func HasPrefix(s, prefix []byte) bool { 356 | return len(s) >= len(prefix) && Equal(s[0:len(prefix)], prefix) 357 | } 358 | // 是否以suffix结尾 359 | func HasSuffix(s, suffix []byte) bool { 360 | return len(s) >= len(suffix) && Equal(s[len(s)-len(suffix):], suffix) 361 | } 362 | ``` 363 | 364 | ### Repeat 365 | 返回b重复count次后的结果. 366 | ```go 367 | func Repeat(b []byte, count int) []byte { 368 | nb := make([]byte, len(b)*count) 369 | bp := 0 370 | for i := 0; i < count; i++ { 371 | for j := 0; j < len(b); j++ { 372 | nb[bp] = b[j] 373 | bp++ 374 | } 375 | } 376 | return nb 377 | } 378 | ``` 379 | 380 | ### Map 381 | 对s中的每个rune调用mapping方法, 如果mapping返回的rune小于0则丢弃该rune, 否则将mapping的返回值编码为byte数组后累积起来, 最后一块返回. 382 | ```go 383 | func Map(mapping func(r rune) rune, s []byte) []byte { 384 | maxbytes := len(s) 385 | nbytes := 0 // 当前累积的字节数 386 | b := make([]byte, maxbytes) 387 | 388 | for i := 0; i < len(s); { 389 | // 得到rune 390 | wid := 1 391 | r := rune(s[i]) 392 | if r >= utf8.RuneSelf { 393 | r, wid = utf8.DecodeRune(s[i:]) 394 | } 395 | 396 | r = mapping(r) 397 | if r >= 0 { 398 | if nbytes+utf8.RuneLen(r) > maxbytes { 399 | // 增大buffer 400 | maxbytes = maxbytes*2 + utf8.UTFMax 401 | nb := make([]byte, maxbytes) 402 | copy(nb, b[0:nbytes]) 403 | b = nb 404 | } 405 | // 将mapping的结果编码后保存到b中 406 | nbytes += utf8.EncodeRune(b[nbytes:maxbytes], r) 407 | } 408 | i += wid 409 | } 410 | 411 | return b[0:nbytes] 412 | } 413 | ``` 414 | 415 | ### ToUpper, ToLower 416 | 都是对Map方法的包装 417 | ```go 418 | func ToUpper(s []byte) []byte { return Map(unicode.ToUpper, s) } 419 | func ToLower(s []byte) []byte { return Map(unicode.ToLower, s) } 420 | ``` 421 | 422 | 423 | 424 | links 425 | ----- 426 | + [目录](../golang) 427 | + 上一节: [Pkg expvar](Pkg-expvar.md) 428 | -------------------------------------------------------------------------------- /golang/Pkg-expvar.go: -------------------------------------------------------------------------------- 1 | Pkg expvar 2 | ---- 3 | 4 | package expvar提供了通过web查看应用当前状态的方式. 5 | 6 | 7 | 8 | 9 | links 10 | ----- 11 | + [目录](../golang) 12 | + 上一节: [Pkg sort](Pkg-sort.md) 13 | -------------------------------------------------------------------------------- /golang/Pkg-expvar.md: -------------------------------------------------------------------------------- 1 | Pkg expvar 2 | ---- 3 | 4 | Package expvar是用于获取public variables的标准接口. 通过http访问/debug/vars, 即可得到json格式的public variables. 5 | expvar默认publish了2个variable: cmdline和memstats, 分别用于获取程序启动时的命令行参数和当前内存使用情况. 6 | 可根据自己的需要publish其他variable. 7 | 8 | ### init 9 | 初始化操作. 10 | ```go 11 | func init() { 12 | http.HandleFunc("/debug/varss", expvarHandler) 13 | // publish cmdline and memstats 14 | Publish("cmdline", Func(cmdline)) 15 | Publish("memstats", Func(memstats)) 16 | } 17 | 18 | func expvarHandler(w http.ResponseWriter, r *http.Request) { 19 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 20 | fmt.Fprintf(w, "{\n") 21 | first := true 22 | // 输出所有已publish的variable 23 | Do(func(kv KeyValue) { 24 | if !first { 25 | fmt.Fprintf(w, ",\n") 26 | } 27 | first = false 28 | fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value) 29 | }) 30 | fmt.Fprintf(w, "\n}\n") 31 | } 32 | 33 | // 存储已publish的variables 34 | var ( 35 | mutex sync.RWMutex 36 | // 每个publish的variable需要实现Var接口, Var接口只定义了一个方法: String 37 | vars map[string]Var = make(map[string]Var) 38 | ) 39 | 40 | func Do(f func(KeyValue)) { 41 | mutex.RLock() 42 | defer mutex.RUnlock() 43 | for k, v := range vars { 44 | f(KeyValue{k, v}) 45 | } 46 | } 47 | ``` 48 | 49 | ### Puslish 50 | 将variable添加到`expvar.vars`中. 51 | ```go 52 | func Publish(name string, v Var) { 53 | mutex.Lock() 54 | defer mutex.Unlock() 55 | // name已存在时, 会引起panic 56 | if _, existing := vars[name]; existing { 57 | log.Panicln("Reuse of exported var name:", name) 58 | } 59 | vars[name] = v 60 | } 61 | ``` 62 | 63 | ### Var 64 | 所有需要publish的variable都必须实现Var接口. 65 | ```go 66 | type Var interface { 67 | String() string 68 | } 69 | ``` 70 | package expvar提供了一些实现Var接口的类型. 71 | 72 | ### Int, Float, String 73 | Int是对int的包装, 实现Var接口, 并提供了一些原子操作. 74 | ```go 75 | type Int struct { 76 | i int64 77 | mu sync.RWMutex 78 | } 79 | // 实现Var接口 80 | func (v *Int) String() string { 81 | v.mu.RLock() 82 | defer v.mu.RUnlock() 83 | return strconv.FormatInt(v.i, 10) 84 | } 85 | // 原子操作 86 | func (v *Int) Add(delta int64) { 87 | v.mu.Lock() 88 | defer v.mu.Unlock() 89 | v.i += delta 90 | } 91 | // 原子操作 92 | func (v *Int) Set(value int64) { 93 | v.mu.Lock() 94 | defer v.mu.Unlock() 95 | v.i = value 96 | } 97 | ``` 98 | 类似的, Float是对float64的包装, 实现Var接口, 并提供了一些原子操作. 99 | ```go 100 | type Float struct { 101 | f float64 102 | mu sync.RWMutex 103 | } 104 | func (v *Float) String() string { 105 | v.mu.RLock() 106 | defer v.mu.RUnlock() 107 | return strconv.FormatFloat(v.f, 'g', -1, 64) 108 | } 109 | func (v *Float) Add(delta float64) { 110 | v.mu.Lock() 111 | defer v.mu.Unlock() 112 | v.f += delta 113 | } 114 | func (v *Float) Set(value float64) { 115 | v.mu.Lock() 116 | defer v.mu.Unlock() 117 | v.f = value 118 | } 119 | ``` 120 | String也是如此. 121 | ```go 122 | type String struct { 123 | s string 124 | mu sync.RWMutex 125 | } 126 | func (v *String) String() string { 127 | v.mu.RLock() 128 | defer v.mu.RUnlock() 129 | return strconv.Quote(v.s) 130 | } 131 | func (v *String) Set(value string) { 132 | v.mu.Lock() 133 | defer v.mu.Unlock() 134 | v.s = value 135 | } 136 | ``` 137 | 138 | ### Map 139 | Map是对`map[string]Var`的包装, 同时其自身也实现了Var接口. 140 | ```go 141 | type Map struct { 142 | m map[string]Var 143 | mu sync.RWMutex 144 | } 145 | 146 | // map中的一个entry 147 | type KeyValue struct { 148 | Key string 149 | Value Var 150 | } 151 | 152 | // 实现了Var接口. 153 | func (v *Map) String() string { 154 | v.mu.RLock() 155 | defer v.mu.RUnlock() 156 | var b bytes.Buffer 157 | fmt.Fprintf(&b, "{") 158 | first := true 159 | for key, val := range v.m { 160 | if !first { 161 | fmt.Fprintf(&b, ", ") 162 | } 163 | fmt.Fprintf(&b, "\"%s\": %v", key, val) 164 | first = false 165 | } 166 | fmt.Fprintf(&b, "}") 167 | return b.String() 168 | } 169 | 170 | func (v *Map) Init() *Map { 171 | v.m = make(map[string]Var) 172 | return v 173 | } 174 | 175 | // ... 省略了一些方法 176 | 177 | // 对Map中每对KeyValue调用f 178 | func (v *Map) Do(f func(KeyValue)) { 179 | v.mu.RLock() 180 | defer v.mu.RUnlock() 181 | for k, v := range v.m { 182 | f(KeyValue{k, v}) 183 | } 184 | } 185 | ``` 186 | 187 | ### Func 188 | 以上几种Var类型具有一个共同点: 他们都是`静态值`. 189 | Func可用于动态的获取某个值. 190 | ```go 191 | type Func func() interface{} 192 | // 为Func实现Var接口 193 | func (f Func) String() string { 194 | v, _ := json.Marshal(f()) 195 | return string(v) 196 | } 197 | ``` 198 | Publish Func类型的variable之后, 访问/debug/vars将会调用该variable的String方法, 而String方法中会调用Func函数, 因此可动态的获取值. 199 | cmdline和memstats是对Func的典型应用: 200 | ```go 201 | func cmdline() interface{} { 202 | return os.Args 203 | } 204 | 205 | func memstats() interface{} { 206 | stats := new(runtime.MemStats) 207 | runtime.ReadMemStats(stats) 208 | return *stats 209 | } 210 | ``` 211 | 在初始化时, 将cmdline和memstats函数强制转换为Func, 之后再Publish: `Publish("cmdline", Func(cmdline))` 212 | 213 | 214 | ### 示例 215 | 统计访问/debug/vars的次数. 216 | ```go 217 | func expvarMain() { 218 | expvar.Publish("visitCnt", expvar.Func(visitCnt)) 219 | 220 | err := http.ListenAndServe(":8080", nil) 221 | if err != nil { 222 | os.Exit(1) 223 | } 224 | } 225 | 226 | var times = 0 227 | 228 | func visitCnt() interface{} { 229 | times++ 230 | return times 231 | } 232 | ``` 233 | 启动程序后, 可在浏览器中访问`http://localhost:8080/debug/vars`, 刷新可看到visitCnt值的变化. 234 | 235 | 236 | links 237 | ----- 238 | + [目录](../golang) 239 | + 上一节: [Pkg sort](Pkg-sort.md) 240 | + 下一节: [Pkg bytes](Pkg-bytes.md) 241 | -------------------------------------------------------------------------------- /golang/Pkg-ioutil.md: -------------------------------------------------------------------------------- 1 | Pkg ioutil 2 | ---- 3 | 4 | ioutil包提供了一些io操作的便利方法. 5 | 6 | ### ReadAll 7 | 从指定的io.Reader对象中读取数据, 直到发生error或者到达文件末尾, 返回读取的所有数据. 8 | ```go 9 | func ReadAll(r io.Reader) ([]byte, error) { 10 | return readAll(r, bytes.MinRead) 11 | } 12 | 13 | // 第二个参数表示初始申请的内存块的大小 14 | // 如果该值过大会导致内存的浪费; 如果过小, 则会导致频繁的重新申请内存 15 | func readAll(r io.Reader, capacity int64) (b []byte, err error) { 16 | buf := bytes.NewBuffer(make([]byte, 0, capacity)) 17 | defer func() { 18 | // readAll方法试图将io.Reader(通常是文件)的所有内容读进内存 19 | // 如果待读取的数据量过大, 需要申请的内存可能超过操作系统限制 20 | // 此时将导致buf.ReadFrom方法发生panic, recover该panic时能得到bytes.ErrTooLarge 21 | // 在defer调用中, 只处理上述提到的panic, 将其转换为err返回给调用方, 而保持其他未知的panic 22 | e := recover() 23 | if e == nil { 24 | return 25 | } 26 | if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge { 27 | err = panicErr 28 | } else { 29 | panic(e) 30 | } 31 | }() 32 | _, err = buf.ReadFrom(r) 33 | return buf.Bytes(), err 34 | } 35 | ``` 36 | 37 | ### ReadFile 38 | ReadFile和ReadAll方法类似, 区别在于ReadFile读取的是指定文件的所有内容. 39 | ```go 40 | func ReadFile(filename string) ([]byte, error) { 41 | f, err := os.Open(filename) 42 | if err != nil { 43 | return nil, err 44 | } 45 | defer f.Close() 46 | 47 | // 接下来试图根据文件的大小, 给定一个合适的capacity参数(在调用readAll方法时会用到). 48 | // 虽然FileInfo返回的文件大小不一定准确, 但仍然值得一试 49 | var n int64 50 | 51 | if fi, err := f.Stat(); err == nil { 52 | // Don't preallocate a huge buffer, just in case. 53 | if size := fi.Size(); size < 1e9 { 54 | n = size 55 | } 56 | } 57 | return readAll(f, n+bytes.MinRead) 58 | } 59 | ``` 60 | 61 | ### Readdir 62 | 获取指定目录下的文件列表, 并根据文件名进行排序. 63 | ```go 64 | func ReadDir(dirname string) ([]os.FileInfo, error) { 65 | f, err := os.Open(dirname) 66 | if err != nil { 67 | return nil, err 68 | } 69 | list, err := f.Readdir(-1) 70 | f.Close() 71 | if err != nil { 72 | return nil, err 73 | } 74 | // 排序 75 | sort.Sort(byName(list)) 76 | return list, nil 77 | } 78 | 79 | // byName实现了sort.Interface接口所需的Len, Less, Swap方法. 80 | // 以方便根据文件名进行排序. 81 | type byName []os.FileInfo 82 | func (f byName) Len() int { return len(f) } 83 | func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() } 84 | func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] } 85 | ``` 86 | 87 | ### NopCloser 88 | 将io.Reader对象包装成io.ReadCloser对象. 89 | ```go 90 | func NopCloser(r io.Reader) io.ReadCloser { 91 | return nopCloser{r} 92 | } 93 | 94 | // nopCloser匿名内嵌io.Reader, 因此nopCloser对象实现了io.Reader接口 95 | // 又因为nopCloser对象具有Close方法, 因此nopCloser对象实现了io.ReadCloser接口 96 | type nopCloser struct { 97 | io.Reader 98 | } 99 | // Close方法什么也不做, 只是为了实现接口而存在 100 | func (nopCloser) Close() error { return nil } 101 | ``` 102 | 103 | ### Discard 104 | Discard是一个io.Writer对象, 该对象相当于bash中的/dev/null, 所有写往Discard的数据都将被丢弃, 并保证写入操作肯定成功. 105 | ```go 106 | var Discard io.Writer = devNull(0) 107 | type devNull int 108 | // 实现io.Writer接口. all Write calls succeed without doing anything. 109 | func (devNull) Write(p []byte) (int, error) { 110 | return len(p), nil 111 | } 112 | ``` 113 | 114 | ### TempFile 115 | 使用指定的文件名前缀, 在指定的目录中, 创建临时文件. 116 | ```go 117 | func TempFile(dir, prefix string) (f *os.File, err error) { 118 | // 如果dir为空, 使用默认的临时目录, 在linux下, 该目录为/tmp 119 | if dir == "" { 120 | dir = os.TempDir() 121 | } 122 | 123 | nconflict := 0 124 | for i := 0; i < 10000; i++ { 125 | name := filepath.Join(dir, prefix+nextSuffix()) 126 | // 同时指定了os.O_CREATE, os.O_EXCL调用OpenFile时, 如果文件已存在, 该方法将返回error 127 | f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) 128 | if os.IsExist(err) { 129 | // 冲突次数超过10时, 调整随机种子 130 | if nconflict++; nconflict > 10 { 131 | rand = reseed() 132 | } 133 | continue 134 | } 135 | break 136 | } 137 | return 138 | } 139 | ``` 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | links 159 | ----- 160 | + [目录](../golang) 161 | + 上一节: [Pkg bufio](Pkg-bufio.md) 162 | + 下一节: [Pkg list](Pkg-list.md) 163 | -------------------------------------------------------------------------------- /golang/Pkg-list.md: -------------------------------------------------------------------------------- 1 | Pkg list 2 | ---- 3 | 4 | list包提供双向链表的实现 5 | 6 | ### List和Element 7 | ```go 8 | // List中的单个元素 9 | type Element struct { 10 | // 前后指针 11 | next, prev *Element 12 | // The list to which this element belongs. 13 | list *List 14 | // 包含的实际值 15 | Value interface{} 16 | } 17 | 18 | type List struct { 19 | // 头指针, 尾指针 20 | front, back *Element 21 | len int 22 | } 23 | ``` 24 | 25 | ### Next和Prev 26 | ```go 27 | // 获取e的后一个Element. nil表示e处于链表的末尾 28 | func (e *Element) Next() *Element { return e.next } 29 | // 获取e的前一个Element. nil表示e处于链表的开头 30 | func (e *Element) Prev() *Element { return e.prev } 31 | ``` 32 | 33 | ### Init和New 34 | Init重置list为初始状态 35 | ```go 36 | func (l *List) Init() *List { 37 | // 将list的各个字段设置为对应的零值 38 | // new(List)返回的*List已经是可以使用的List的, 并不需要调用一次Init后再使用. 39 | l.front = nil 40 | l.back = nil 41 | l.len = 0 42 | return l 43 | } 44 | // 创建List 45 | func New() *List { return new(List) } 46 | ``` 47 | 48 | ### Front和Back 49 | ```go 50 | // 返回list中的第一个Element 51 | func (l *List) Front() *Element { return l.front } 52 | // 返回list中的最后一个Element 53 | func (l *List) Back() *Element { return l.back } 54 | ``` 55 | 56 | ### Remove 57 | 将e从list中删除, 并返回e包含的Value 58 | ```go 59 | func (l *List) Remove(e *Element) interface{} { 60 | l.remove(e) 61 | e.list = nil // do what remove does not 62 | return e.Value 63 | } 64 | // 执行实际的删除操作 65 | func (l *List) remove(e *Element) { 66 | // 判断e是否属于list 67 | if e.list != l { 68 | return 69 | } 70 | 71 | if e.prev == nil { 72 | // 如果e处于链表的开头, 将链表的头指针指向e的下一个Element 73 | l.front = e.next 74 | } else { 75 | // 将e的前一个Element的next指针指向e的后一个Element 76 | e.prev.next = e.next 77 | } 78 | if e.next == nil { 79 | // 如果e处于链表的末尾, 将链表的尾指针指向e的前一个Element 80 | l.back = e.prev 81 | } else { 82 | // 将e的后一个Element的prev指针指向e的前一个Element 83 | e.next.prev = e.prev 84 | } 85 | 86 | e.prev = nil 87 | e.next = nil 88 | l.len-- 89 | } 90 | ``` 91 | 92 | ### insertBefore和insertAfter 93 | ```go 94 | // 在mark之前插入e 95 | func (l *List) insertBefore(e *Element, mark *Element) { 96 | if mark.prev == nil { 97 | // 头指针指向e 98 | l.front = e 99 | } else { 100 | // 将mark的前一个Element的next指针指向e 101 | mark.prev.next = e 102 | } 103 | // 调整e和mark的前后指针 104 | e.prev = mark.prev 105 | mark.prev = e 106 | e.next = mark 107 | l.len++ 108 | } 109 | // 在mark之后插入e 110 | func (l *List) insertAfter(e *Element, mark *Element) { 111 | if mark.next == nil { 112 | // 尾指针指向e 113 | l.back = e 114 | } else { 115 | // 将mark的后一个Element的prev指针指向e 116 | mark.next.prev = e 117 | } 118 | // 调整e和mark的前后指针 119 | e.next = mark.next 120 | mark.next = e 121 | e.prev = mark 122 | l.len++ 123 | } 124 | ``` 125 | 126 | ### insertFront和insertBack 127 | ```go 128 | // 在链表的开头插入e 129 | func (l *List) insertFront(e *Element) { 130 | if l.front == nil { 131 | // 空链表单独处理 132 | l.front, l.back = e, e 133 | e.prev, e.next = nil, nil 134 | l.len = 1 135 | return 136 | } 137 | l.insertBefore(e, l.front) 138 | } 139 | // 在链表的末尾插入e 140 | func (l *List) insertBack(e *Element) { 141 | if l.back == nil { 142 | // 空链表单独处理 143 | l.front, l.back = e, e 144 | e.prev, e.next = nil, nil 145 | l.len = 1 146 | return 147 | } 148 | l.insertAfter(e, l.back) 149 | } 150 | ``` 151 | 152 | ### PushFront和PushBack 153 | ```go 154 | // 将value包装成Element, 并将Element插入链表开头 155 | func (l *List) PushFront(value interface{}) *Element { 156 | e := &Element{nil, nil, l, value} 157 | l.insertFront(e) 158 | return e 159 | } 160 | // 将value包装成Element, 并将Element插入链表末尾 161 | func (l *List) PushBack(value interface{}) *Element { 162 | e := &Element{nil, nil, l, value} 163 | l.insertBack(e) 164 | return e 165 | } 166 | ``` 167 | 168 | ### InsertBefore和InsertAfter 169 | ```go 170 | // 将value包装成Element, 并将Element插入mark之前 171 | func (l *List) InsertBefore(value interface{}, mark *Element) *Element { 172 | if mark.list != l { 173 | return nil 174 | } 175 | e := &Element{nil, nil, l, value} 176 | l.insertBefore(e, mark) 177 | return e 178 | } 179 | // 将value包装成Element, 并将Element插入mark之后 180 | func (l *List) InsertAfter(value interface{}, mark *Element) *Element { 181 | if mark.list != l { 182 | return nil 183 | } 184 | e := &Element{nil, nil, l, value} 185 | l.insertAfter(e, mark) 186 | return e 187 | } 188 | ``` 189 | 190 | ### MoveToFront和MoveToBack 191 | ```go 192 | // 将e移动到链表的开头 193 | func (l *List) MoveToFront(e *Element) { 194 | if e.list != l || l.front == e { 195 | return 196 | } 197 | // 先将e删除, 然后在链表开头插入 198 | l.remove(e) 199 | l.insertFront(e) 200 | } 201 | 202 | // 将e移动到链表的末尾 203 | func (l *List) MoveToBack(e *Element) { 204 | if e.list != l || l.back == e { 205 | return 206 | } 207 | // 先将e删除, 然后在链表末尾插入 208 | l.remove(e) 209 | l.insertBack(e) 210 | } 211 | ``` 212 | 213 | ### PushFrontList和PushBackList 214 | ```go 215 | // 将ol整体插入链表的开头 216 | func (l *List) PushFrontList(ol *List) { 217 | first := ol.Front() 218 | // 从ol的尾部开始, 依次将ol的每个value插入链表的开头 219 | for e := ol.Back(); e != nil; e = e.Prev() { 220 | l.PushFront(e.Value) 221 | if e == first { 222 | break 223 | } 224 | } 225 | } 226 | // 将ol整体插入链表的末尾 227 | func (l *List) PushBackList(ol *List) { 228 | last := ol.Back() 229 | // 从ol的头部开始, 依次将ol的每个value插入链表的末尾 230 | for e := ol.Front(); e != nil; e = e.Next() { 231 | l.PushBack(e.Value) 232 | if e == last { 233 | break 234 | } 235 | } 236 | } 237 | ``` 238 | 239 | ### Len 240 | 返回链表的长度 241 | ```go 242 | func (l *List) Len() int { return l.len } 243 | ``` 244 | 245 | 246 | 247 | links 248 | ----- 249 | + [目录](../golang) 250 | + 上一节: [Pkg ioutil](Pkg-ioutil.md) 251 | + 下一节: [Pkg log](Pkg-log.md) 252 | -------------------------------------------------------------------------------- /golang/Pkg-log.md: -------------------------------------------------------------------------------- 1 | Pkg log 2 | ---- 3 | 4 | Package log实现了简单的日志功能. 定义了类型Logger, 用于输出格式化日志. 5 | 同时, 预定义了名为std的Logger对象, 用于输出日志到stderr. 6 | 包中的Fatal方法将在输出日志消息后调用os.Exit(1), 而Panic方法将在输出日志消息后调用panic. 7 | 8 | ### Logger 9 | Logger可在多个goroutines中并发使用, 其内部使用sync.Mutex进行同步. 10 | ```go 11 | type Logger struct { 12 | // 同步锁 13 | mu sync.Mutex 14 | // 日志消息前缀 15 | prefix string 16 | // 用于控制日期, 时间, 文件名等信息的输出 17 | flag int 18 | // 输出的目标 19 | out io.Writer 20 | buf []byte 21 | } 22 | ``` 23 | flag可取以下值: 24 | ```go 25 | const ( 26 | // 输出日期: 2009/01/23 27 | Ldate = 1 << iota 28 | // 输出时间: 01:23:23 29 | Ltime 30 | // 输出毫秒值: 01:23:23.123123 31 | Lmicroseconds 32 | // 输出文件的绝对路径名和行数: /a/b/c/d.go:23 33 | Llongfile 34 | // 输出文件名和行数: d.go:23, 设置了此flag, 会覆盖Llongfile 35 | Lshortfile 36 | // 同时输出日期和时间 37 | LstdFlags = Ldate | Ltime 38 | ) 39 | ``` 40 | 若想同时输出日期和完整的文件名, 可将flag设置为: Ldate | Llongfile. 41 | 42 | ### Logger.New 43 | 创建Logger对象. 44 | ```go 45 | func New(out io.Writer, prefix string, flag int) *Logger { 46 | return &Logger{out: out, prefix: prefix, flag: flag} 47 | } 48 | ``` 49 | 50 | ### Logger.Output 51 | 输出日志消息. 52 | ```go 53 | // calldepth指定调用深度, s表示要输出的日志消息 54 | func (l *Logger) Output(calldepth int, s string) error { 55 | now := time.Now() // get this early. 56 | var file string // 文件名 57 | var line int // 行数 58 | l.mu.Lock() 59 | defer l.mu.Unlock() 60 | if l.flag&(Lshortfile|Llongfile) != 0 { 61 | // runtime.Caller用于返回调用堆栈信息, 该操作是昂贵的, 因此先释放锁, 避免阻塞其他goroutine的日志输出 62 | l.mu.Unlock() 63 | var ok bool 64 | _, file, line, ok = runtime.Caller(calldepth) 65 | // 考虑获取堆栈信息失败的情况 66 | if !ok { 67 | file = "???" 68 | line = 0 69 | } 70 | l.mu.Lock() 71 | } 72 | // 重置缓冲区 73 | l.buf = l.buf[:0] 74 | l.formatHeader(&l.buf, now, file, line) 75 | // 将日志消息也写入缓冲区 76 | l.buf = append(l.buf, s...) 77 | // 如果最后一个字符不是换行符, 则在末尾加入'\n' 78 | if len(s) > 0 && s[len(s)-1] != '\n' { 79 | l.buf = append(l.buf, '\n') 80 | } 81 | // 写入io.Writer 82 | _, err := l.out.Write(l.buf) 83 | return err 84 | } 85 | ``` 86 | formatHeader方法将prefix, flag等信息写入缓冲区. 87 | ```go 88 | func (l *Logger) formatHeader(buf *[]byte, t time.Time, file string, line int) { 89 | // 写入prefix 90 | *buf = append(*buf, l.prefix...) 91 | if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 { 92 | if l.flag&Ldate != 0 { // 写入日期 93 | year, month, day := t.Date() 94 | itoa(buf, year, 4) 95 | *buf = append(*buf, '/') 96 | itoa(buf, int(month), 2) 97 | *buf = append(*buf, '/') 98 | itoa(buf, day, 2) 99 | *buf = append(*buf, ' ') 100 | } 101 | if l.flag&(Ltime|Lmicroseconds) != 0 { // 写入时间 102 | hour, min, sec := t.Clock() 103 | itoa(buf, hour, 2) 104 | *buf = append(*buf, ':') 105 | itoa(buf, min, 2) 106 | *buf = append(*buf, ':') 107 | itoa(buf, sec, 2) 108 | if l.flag&Lmicroseconds != 0 { 109 | *buf = append(*buf, '.') 110 | itoa(buf, t.Nanosecond()/1e3, 6) 111 | } 112 | *buf = append(*buf, ' ') 113 | } 114 | } 115 | if l.flag&(Lshortfile|Llongfile) != 0 { // 写入文件名和行数 116 | if l.flag&Lshortfile != 0 { 117 | short := file 118 | for i := len(file) - 1; i > 0; i-- { 119 | if file[i] == '/' { 120 | short = file[i+1:] 121 | break 122 | } 123 | } 124 | file = short 125 | } 126 | *buf = append(*buf, file...) 127 | *buf = append(*buf, ':') 128 | itoa(buf, line, -1) 129 | *buf = append(*buf, ": "...) 130 | } 131 | } 132 | ``` 133 | 综上, 每一个日志消息包含3个部分, 从头到尾依次是: 134 | + prefix, 创建Logger时指定. 135 | + flag对应的信息, 创建Logger时指定. 根据flag的不同取值, 此处可能包含日期, 时间, 文件名等信息. 136 | + 真实的日志消息. 每次调用Output时指定. 137 | 138 | ### 格式化输出方法 139 | 这些方法都在内部调用Logger.Output, 其calldepth设定为2. 140 | ```go 141 | func (l *Logger) Printf(format string, v ...interface{}) { 142 | l.Output(2, fmt.Sprintf(format, v...)) 143 | } 144 | 145 | func (l *Logger) Print(v ...interface{}) { l.Output(2, fmt.Sprint(v...)) } 146 | 147 | func (l *Logger) Println(v ...interface{}) { l.Output(2, fmt.Sprintln(v...)) } 148 | 149 | func (l *Logger) Fatal(v ...interface{}) { 150 | l.Output(2, fmt.Sprint(v...)) 151 | // 结束程序 152 | os.Exit(1) 153 | } 154 | 155 | func (l *Logger) Fatalf(format string, v ...interface{}) { 156 | l.Output(2, fmt.Sprintf(format, v...)) 157 | os.Exit(1) 158 | } 159 | 160 | func (l *Logger) Fatalln(v ...interface{}) { 161 | l.Output(2, fmt.Sprintln(v...)) 162 | os.Exit(1) 163 | } 164 | 165 | func (l *Logger) Panic(v ...interface{}) { 166 | s := fmt.Sprint(v...) 167 | l.Output(2, s) 168 | panic(s) 169 | } 170 | 171 | func (l *Logger) Panicf(format string, v ...interface{}) { 172 | s := fmt.Sprintf(format, v...) 173 | l.Output(2, s) 174 | panic(s) 175 | } 176 | 177 | func (l *Logger) Panicln(v ...interface{}) { 178 | s := fmt.Sprintln(v...) 179 | l.Output(2, s) 180 | panic(s) 181 | } 182 | ``` 183 | 184 | ### Logger.Flags和Logger.SetFlags 185 | 返回或设置Logger的flag. 186 | ```go 187 | func (l *Logger) Flags() int { 188 | l.mu.Lock() 189 | defer l.mu.Unlock() 190 | return l.flag 191 | } 192 | 193 | func (l *Logger) SetFlags(flag int) { 194 | l.mu.Lock() 195 | defer l.mu.Unlock() 196 | l.flag = flag 197 | } 198 | ``` 199 | 200 | ### Logger.Prefix和Logger.SetPrefix 201 | 返回或设置Logger的prefix. 202 | ```go 203 | func (l *Logger) Prefix() string { 204 | l.mu.Lock() 205 | defer l.mu.Unlock() 206 | return l.prefix 207 | } 208 | 209 | func (l *Logger) SetPrefix(prefix string) { 210 | l.mu.Lock() 211 | defer l.mu.Unlock() 212 | l.prefix = prefix 213 | } 214 | ``` 215 | 216 | ### Logger.SetOutput 217 | 设置Logger的输出目标. 218 | ```go 219 | func SetOutput(w io.Writer) { 220 | std.mu.Lock() 221 | defer std.mu.Unlock() 222 | std.out = w 223 | } 224 | ``` 225 | 226 | ### std 227 | std是package内部定义的一个Logger. 228 | ```go 229 | var std = New(os.Stderr, "", LstdFlags) 230 | ``` 231 | 232 | 233 | 234 | links 235 | ----- 236 | + [目录](../golang) 237 | + 上一节: [Pkg list](Pkg-list.md) 238 | + 下一节: [Pkg sort](Pkg-sort.md) 239 | -------------------------------------------------------------------------------- /golang/Pkg-sort.md: -------------------------------------------------------------------------------- 1 | Pkg sort 2 | ---- 3 | 4 | Package sort为slice或者自定义的集合提供排序功能. 5 | 6 | ### Interface 7 | Interface定义了排序所需实现的接口. 8 | ```go 9 | type Interface interface { 10 | // 集合中元素的个数 11 | Len() int 12 | // 第i个元素和第j个元素的比较 13 | Less(i, j int) bool 14 | // 交换第i个元素和第j个元素的位置 15 | Swap(i, j int) 16 | } 17 | ``` 18 | 如果想要使用sort包提供的排序功能, 相应的类型就必须实现Interface接口. 19 | 20 | ### Sort 21 | Sort方法实现排序. 22 | ```go 23 | func Sort(data Interface) { 24 | n := data.Len() 25 | maxDepth := 0 26 | for i := n; i > 0; i >>= 1 { 27 | maxDepth++ 28 | } 29 | maxDepth *= 2 30 | quickSort(data, 0, n, maxDepth) 31 | } 32 | ``` 33 | 内部使用堆排序和快速排序结合的算法: 34 | ```go 35 | func quickSort(data Interface, a, b, maxDepth int) { 36 | for b-a > 7 { 37 | if maxDepth == 0 { 38 | heapSort(data, a, b) 39 | return 40 | } 41 | maxDepth-- 42 | mlo, mhi := doPivot(data, a, b) 43 | // Avoiding recursion on the larger subproblem guarantees 44 | // a stack depth of at most lg(b-a). 45 | if mlo-a < b-mhi { 46 | quickSort(data, a, mlo, maxDepth) 47 | a = mhi // i.e., quickSort(data, mhi, b) 48 | } else { 49 | quickSort(data, mhi, b, maxDepth) 50 | b = mlo // i.e., quickSort(data, a, mlo) 51 | } 52 | } 53 | if b-a > 1 { 54 | insertionSort(data, a, b) 55 | } 56 | } 57 | ``` 58 | 59 | ### IsSorted 60 | 判断数据是否是升序排列的. 61 | ```go 62 | func IsSorted(data Interface) bool { 63 | n := data.Len() 64 | for i := n - 1; i > 0; i-- { 65 | // 如果出现了降序, 则直接返回false 66 | if data.Less(i, i-1) { 67 | return false 68 | } 69 | } 70 | return true 71 | } 72 | ``` 73 | 74 | ### IntSlice 75 | 为[]int类型实现Interface接口. 76 | ```go 77 | type IntSlice []int 78 | func (p IntSlice) Len() int { return len(p) } 79 | func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] } 80 | func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 81 | func (p IntSlice) Sort() { Sort(p) } 82 | ``` 83 | 对于使用者来说, 之需要这样: 84 | ```go 85 | ints := []int{1, 9, 3, -1, 18} 86 | // 强制转换 87 | intSlice := sort.IntSlice(ints) 88 | intSlice.Sort() 89 | fmt.Println(ints) // 输出: [-1 1 3 9 18] 90 | ``` 91 | 92 | ### Float64Slice, StringSlice 93 | 类似的, sort包还为[]float64和[]string实现了Interface接口, 以方便我们的使用. 94 | ```go 95 | type Float64Slice []float64 96 | func (p Float64Slice) Len() int { return len(p) } 97 | func (p Float64Slice) Less(i, j int) bool { return p[i] < p[j] || math.IsNaN(p[i]) && !math.IsNaN(p[j]) } 98 | func (p Float64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 99 | func (p Float64Slice) Sort() { Sort(p) } 100 | 101 | type StringSlice []string 102 | func (p StringSlice) Len() int { return len(p) } 103 | func (p StringSlice) Less(i, j int) bool { return p[i] < p[j] } 104 | func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 105 | func (p StringSlice) Sort() { Sort(p) } 106 | ``` 107 | 108 | ### Ints, Float64s, Strings 109 | 更为贴心的是, sort包还为我们可以更为简便的排序方法. 110 | ```go 111 | func Ints(a []int) { Sort(IntSlice(a)) } 112 | func Float64s(a []float64) { Sort(Float64Slice(a)) } 113 | func Strings(a []string) { Sort(StringSlice(a)) } 114 | ``` 115 | 这样一来, 想要对[]int排序就更简单了: 116 | ```go 117 | ints := []int{1, 9, 3, -1, 18} 118 | sort.Ints(ints) 119 | fmt.Println(ints) 120 | ``` 121 | 122 | ### IntsAreSorted, Float64sAreSorted, StringsAreSorted 123 | 这3个方法也是为了方便调用者使用而存在的. 124 | ```go 125 | // 判断[]int是否按升序排列 126 | func IntsAreSorted(a []int) bool { return IsSorted(IntSlice(a)) } 127 | func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Slice(a)) } 128 | func StringsAreSorted(a []string) bool { return IsSorted(StringSlice(a)) } 129 | ``` 130 | 131 | ### 为自定义类型实现Interface接口 132 | 如果我们自定义了Person类型, 那么如何为[]Person排序呢? 最简单的方法就是让[]Person实现Interface接口. 133 | ```go 134 | type Person struct { 135 | Name string 136 | Age int 137 | } 138 | type PersonSlice []Person 139 | 140 | func (ps PersonSlice) Len() int { 141 | return len(ps) 142 | } 143 | func (ps PersonSlice) Less(i, j int) bool { 144 | return ps[i].Name < ps[j].Name 145 | } 146 | func (ps PersonSlice) Swap(i, j int) { 147 | ps[i], ps[j] = ps[j], ps[i] 148 | } 149 | 150 | func personSort() { 151 | ps := []Person{{"xing", 25}, {"min", 30}, {"yong", 29}} 152 | sort.Sort(PersonSlice(ps)) 153 | fmt.Println(ps) // [{min 30} {xing 25} {yong 29}] 154 | } 155 | ``` 156 | 如果不想按升序排序, 想要降序排列, 之需要稍微更改一下Less方法即可. 157 | ```go 158 | func (ps PersonSlice) Less(i, j int) bool { 159 | return ps[i].Name > ps[j].Name 160 | } 161 | ``` 162 | 如果想要按Age排列也很简单. 163 | ```go 164 | func (ps PersonSlice) Less(i, j int) bool { 165 | return ps[i].Age < ps[j].Age 166 | } 167 | ``` 168 | 169 | ### Search 170 | 排序总是和查找不分家, 为此, sort包也实现了二分查找法. 171 | ```go 172 | func Search(n int, f func(int) bool) int { 173 | i, j := 0, n 174 | for i < j { 175 | // 取得中间索引 176 | h := i + (j-i)/2 177 | if !f(h) { 178 | i = h + 1 179 | } else { 180 | j = h 181 | } 182 | } 183 | return i 184 | } 185 | ``` 186 | Search方法的参数n和f需要满足条件: 187 | + 存在索引x, 使得当i属于[0,x]时, f(i) == false. 且 188 | + 当i属于(x,n)时, f(i) == true. 189 | + Search方法返回x, the first true index. 190 | 191 | ### SearchInts, SearchFloat64s, SearchStrings 192 | 如果想要在已排好序的[]int, []float64, 或者[]string中查找某个值, sort包已经实现了相应的方法. 193 | ```go 194 | // 在a中查找x, 返回x所在的索引. a必须是已经按升序排序的slice. 195 | func SearchInts(a []int, x int) int { 196 | return Search(len(a), func(i int) bool { return a[i] >= x }) 197 | } 198 | func SearchFloat64s(a []float64, x float64) int { 199 | return Search(len(a), func(i int) bool { return a[i] >= x }) 200 | } 201 | func SearchStrings(a []string, x string) int { 202 | return Search(len(a), func(i int) bool { return a[i] >= x }) 203 | } 204 | // 对SearchInts的包装 205 | func (p IntSlice) Search(x int) int { return SearchInts(p, x) } 206 | func (p Float64Slice) Search(x float64) int { return SearchFloat64s(p, x) } 207 | func (p StringSlice) Search(x string) int { return SearchStrings(p, x) } 208 | ``` 209 | 以[]int为例: 210 | ```go 211 | ints := []int{1, 9, 3, -1, 18} 212 | // sort first 213 | sort.IntSlice(ints).Sort() 214 | fmt.Println(sort.SearchInts(ints, 9)) // 3 215 | ``` 216 | 当然, 也可以这样: 217 | ```go 218 | ints := []int{1, 9, 3, -1, 18} 219 | is := sort.IntSlice(ints) 220 | is.Sort() 221 | fmt.Println(is.Search(9)) 222 | ``` 223 | 224 | ### 根据Name查找Person 225 | 如果想要在[]Person中查找出Name为指定值的Person, 可以这样: 226 | ```go 227 | func (ps PersonSlice) Search(name string) Person { 228 | searchFunc := func(i int) bool { 229 | return ps[i].Name >= name 230 | } 231 | // 查找到the fisrt true index, 即第一个使得ps[i].Name >= name成立的i 232 | index := sort.Search(len(ps), searchFunc) 233 | return ps[index] 234 | } 235 | // 使用示例 236 | func personSearch() { 237 | persons := []Person{{"xing", 25}, {"min", 30}, {"yong", 29}} 238 | ps := PersonSlice(persons) 239 | sort.Sort(ps) 240 | fmt.Println(ps.Search("xing")) // {xing 25} 241 | } 242 | ``` 243 | 244 | 245 | 246 | 247 | links 248 | ----- 249 | + [目录](../golang) 250 | + 上一节: [Pkg log](Pkg-log.md) 251 | + 下一节: [Pkg expvar](Pkg-expvar.md) 252 | -------------------------------------------------------------------------------- /golang/README.md: -------------------------------------------------------------------------------- 1 | Index 2 | ----- 3 | 4 | ####Pkg bufio 5 | *2013-01-04* 6 | bufio包提供了带有缓冲功能的Reader和Writer, 应用了`装饰者模式`. bufio.Reader是对io.Reader的包装, 并且实现了io.Reader接口. ...[Read More](golang/Pkg-bufio.md) 7 | 8 | ####Pkg ioutil 9 | *2013-01-05* 10 | ioutil包提供了一些io操作的便利方法....[Read More](golang/Pkg-ioutil.md) 11 | 12 | ####Pkg list 13 | *2013-01-06* 14 | list包提供双向链表的实现...[Read More](golang/Pkg-list.md) 15 | 16 | ####Pkg log 17 | *2013-01-11* 18 | Package log实现了简单的日志功能. 定义了类型Logger, 用于输出格式化日志. 同时, 预定义了名为std的Logger对象, 用于输出日志到stderr. ...[Read More](golang/Pkg-log.md) 19 | 20 | ####Pkg sort 21 | *2013-01-12* 22 | Package sort为slice或者自定义的集合提供排序功能....[Read More](golang/Pkg-sort.md) 23 | 24 | ####Pkg expvar 25 | *2013-01-13* 26 | Package expvar是用于获取public variables的标准接口. 通过http访问/debug/vars, 即可得到json格式的public variables. expvar默认publish了2个variable: cmdline和memstats, 分别用于获取程序启动时的命令行参数和当前内存使用情况. ...[Read More](golang/Pkg-expvar.md) 27 | 28 | ####Pkg bytes 29 | *2013-01-26* 30 | Package bytes实现了一系列操作byte slice的方法....[Read More](golang/Pkg-bytes.md) 31 | 32 | -------------------------------------------------------------------------------- /golang/upload.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "flag" 7 | "fmt" 8 | "github.com/xing4git/cmdutils" 9 | "io/ioutil" 10 | "os" 11 | "regexp" 12 | "sort" 13 | ) 14 | 15 | var ( 16 | readme = bytes.NewBuffer(make([]byte, 0)) 17 | change = bytes.NewBuffer(make([]byte, 0)) 18 | commit = bytes.NewBuffer(make([]byte, 0)) 19 | ) 20 | 21 | var ( 22 | reg = regexp.MustCompile("^_\\d{4}-\\d{2}-\\d{2}-") 23 | filenames = make([]string, 0) 24 | dirname = flag.String("d", "golang", "current dir name") 25 | ) 26 | 27 | func init() { 28 | flag.Parse() 29 | flag.PrintDefaults() 30 | fmt.Println("current dir name: " + *dirname) 31 | } 32 | 33 | func main() { 34 | dir, err := os.Open(".") 35 | checkErr(err) 36 | defer dir.Close() 37 | 38 | fis, err := dir.Readdir(0) 39 | checkErr(err) 40 | 41 | for i := 0; i < len(fis); i++ { 42 | fi := fis[i] 43 | filename := fi.Name() 44 | if reg.Match([]byte(filename)) { 45 | filenames = append(filenames, filename) 46 | } 47 | } 48 | 49 | sort.Strings(filenames) 50 | fmt.Println("filenames: ", filenames, "\n") 51 | 52 | readme.WriteString("Index\n") 53 | readme.WriteString("-----\n\n") 54 | change.WriteString("update README.md;") 55 | 56 | for key, value := range filenames { 57 | realname := value[12:] 58 | readme.WriteString("####" + decorateFilename(realname) + "\n") 59 | 60 | file, err := os.Open(value) 61 | checkErr(err) 62 | defer file.Close() 63 | 64 | readme.WriteString("*" + value[1:11] + "*\n") 65 | buf := bufio.NewReader(file) 66 | line, err := buf.ReadString('\n') 67 | checkErr(err) 68 | readme.WriteString(string(line[0 : len(line)-1])) 69 | line, err = buf.ReadString('\n') 70 | checkErr(err) 71 | readme.WriteString(string(line[0 : len(line)-1])) 72 | readme.WriteString("...[Read More](" + *dirname + "/" + realname + ")\n\n") 73 | 74 | file.Seek(0, os.SEEK_SET) 75 | nbytes, err := ioutil.ReadAll(file) 76 | checkErr(err) 77 | var tempbuf []byte 78 | tempbuf = append(tempbuf, []byte(decorateFilename(realname)+"\n"+"----\n\n")...) 79 | nbytes = append(tempbuf, nbytes...) 80 | 81 | nbytes = append(nbytes, []byte("\n\n"+"links\n"+"-----\n")...) 82 | nbytes = append(nbytes, []byte("+ [目录](../"+*dirname+")\n")...) 83 | if key != 0 { 84 | previous := filenames[key-1][12:] 85 | nbytes = append(nbytes, []byte("+ 上一节: ["+decorateFilename(previous)+"]("+previous+")\n")...) 86 | } 87 | if key != len(filenames)-1 { 88 | next := filenames[key+1][12:] 89 | nbytes = append(nbytes, []byte("+ 下一节: ["+decorateFilename(next)+"]("+next+")\n")...) 90 | } 91 | 92 | pbytes, err := ioutil.ReadFile(realname) 93 | if err == nil && bytes.Equal(pbytes, nbytes) { 94 | fmt.Println("no change file:", realname) 95 | continue 96 | } 97 | 98 | change.WriteString("update " + realname + ";") 99 | err = ioutil.WriteFile(realname, nbytes, 0664) 100 | checkErr(err) 101 | } 102 | 103 | err = ioutil.WriteFile("README.md", readme.Bytes(), 0664) 104 | checkErr(err) 105 | 106 | commit.WriteString("git add .\n") 107 | commit.WriteString("git commit -a -m '" + change.String() + "'\n") 108 | commit.WriteString("git push -u origin master\n") 109 | fmt.Println(commit.String()) 110 | ret, err := cmdutils.BashExecute(commit.String()) 111 | checkErr(err) 112 | fmt.Println(ret) 113 | } 114 | 115 | func decorateFilename(str string) string { 116 | bytes := []byte(str) 117 | var suffixStart int = -1 118 | for i := len(str) - 1; i >= 0; i-- { 119 | if bytes[i] == '.' { 120 | suffixStart = i 121 | break 122 | } 123 | } 124 | 125 | if suffixStart != -1 { 126 | bytes = bytes[:suffixStart] 127 | } 128 | 129 | for pos, v := range bytes { 130 | if v == '-' { 131 | bytes[pos] = ' ' 132 | } 133 | } 134 | 135 | return string(bytes) 136 | } 137 | 138 | func checkErr(err error) { 139 | if err != nil { 140 | fmt.Fprintf(os.Stderr, "error: %s\n", err.Error()) 141 | os.Exit(1) 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /groovy/groovy笔记.md: -------------------------------------------------------------------------------- 1 | In Groovy, if you leave off the parentheses when calling a method with no arguments the compiler assumes you are asking for the corresponding getter or setter method. 2 | 3 | ----- 4 | In Groovy every class has a metaclass. A metaclass is another class that manages the actual invocation process. If you invoke a method on a class that doesnot exist, the call is ultimately intercepted by a method in the metaclass called `methodMissing`. Likewise, accessing a property that doesnot exist eventually calls `propertyMissing` in the metaclass. Customizing the behavior of `methodMissing` and `propertyMissing` is the heart of Groovy runtime metaprogramming. 5 | 6 | ---- 7 | In Groovy, if you donot specify an access modifier, attributes are assumed to be private, and methods are assumed to be public. 8 | 9 | In Java, if you donot add a constructor in a class, the compiler gives you a default constructor for free. In Groovy, however, you get not only the default, but also a map-based constructor that allows you to set any combination of attribute values by supplying them as key-value pairs. 10 | 11 | ``` 12 | class Stadium { 13 | int id 14 | String name 15 | String city 16 | String state 17 | 18 | String toString() { "$name, $city, $state" } 19 | } 20 | 21 | def s = new Stadium(name: 'Angel Stadium', city:'Anaheim', state:'CA') 22 | ``` 23 | 24 | In addition, you can use `as` operator: 25 | 26 | ``` 27 | def s = [name: 'Angel Stadium', city:'Anaheim', state:'CA'] as Stadium 28 | ``` 29 | 30 | ---- 31 | At runtime, compiled Groovy and compiled Java both result in bytecodes for the JVM. To execute code that combines them, all that is necessary is to add a single JAR file to the system. Compilimng and tesing your code requires the Groovy compiler and libraries, but at runtime all you need is your JAR. 32 | 33 | That JAR comes with your Groovy distribution in the `embeddable` subdirectory. If this JAR is added to your classpath you can execute combined Groovy and Java application with the standard `java` command. If you add a Groovy module to a web application, add the groovy-all JAR to the WEB-INFO/lib directory and everything will work normally. 34 | 35 | ---- 36 | The natural tendency when using two different languages is to separate the two codebases and compile them independently. With Groovy and Java that can lead to all sorts of problems, especially when cyclic dependencies are involved. The simplest way to compile Groovy and Java in the same project is to let the `groovyc` compiler handle both codebases. Groovy knows all about Java and is quite capable of handling it. Any compiler flags you would normally send to `javac` work just fine in `groovyc` as well. 37 | 38 | ---- 39 | Groovy 1.6 introduced Abstract Syntax Tree (AST) transformations. The idea is to place annotations on Groovy classes and invoke the compiler, which builds a syntax as usual and then modifies it in interesting ways. 40 | 41 | * @Delegate 42 | 43 | With delegation you wrap an instance of one class inside another. You then implement all the same methods in the outer class that the contained class provides, delegating each call to the corresponding method on the contained object. In this way your class has the same interface as the contained object but is not otherwise related to it. Writing all those "pass-through" methods can be a pain, though. Groovy introduce the @Delegate annotation to take care of all that work for you. 44 | 45 | ``` 46 | class Camera { 47 | void takePicture() { 48 | println("take picture") 49 | } 50 | } 51 | 52 | class Phone { 53 | void dial(String number) { 54 | println("dialing $number") 55 | } 56 | } 57 | 58 | class SmartPhone { 59 | @Delegate Camera camera 60 | @Delegate Phone phone 61 | } 62 | 63 | def sp = new SmartPhone(camera: new Camera(), phone: new Phone()) 64 | sp.takePicture() 65 | sp.dial("13245678908") 66 | ``` 67 | 68 | * Creating immutable objects 69 | 70 | Java has no built-in way to make it impossible to modify an object. There is no `const` keyword in Java, and applying the combination of `static` and `final` to a reference only makes the reference a constant, not the object it references. The only way to make an object immutable in Java is to remove all ways to change it: 71 | 72 | 1. All mutable methods (setters) must be removed. 73 | 2. The class should be marked `final`. 74 | 3. Any contained fields should be `private` and `final`. 75 | 4. Mutable components like arrays should defensively be copied on the way in (through constructors) and the way out (through getters). 76 | 5. `equals`, `hasCode`, and `toString` should all be implemented through fields. 77 | 78 | Groovy has an @Immutable AST transformation, which does everything for you. The @Immutable annotation is very powerful, but it has limitations. You can only apply it to classes that contain primitives or certain library classes, like `String` or `Date`. It also works on classes that contain properties that are also immutable. 79 | 80 | * Creating singletons 81 | 82 | There is an AST transformation called @Singleton. 83 | 84 | ``` 85 | @Singleton 86 | class HelloService { 87 | void sayHi() { 88 | println("hi") 89 | } 90 | } 91 | 92 | HelloService.instance.sayHi() 93 | ``` 94 | 95 | The result is that the class now contains a static property called `instance`, which is the one and only instance of the class. 96 | 97 | ---- 98 | The `parseText` method on `JsonSlurper` converts the JSON data into Groovy maps and lists. 99 | 100 | ``` 101 | String u = 'http://api.icndb.com/jokes/random?limitTo=[nerdy]' 102 | def text = u.toURL().text 103 | def json = new JsonSlurper().parseText(text) 104 | def joke = json?.value?.joke 105 | println joke 106 | ``` 107 | 108 | Generating JSON data uses the groovy.json.JsonBuilder class. 109 | 110 | 111 | 112 | 113 | 114 | ### switch statement 115 | 116 | Switch supports the following kinds of comparisions: 117 | 118 | * Class case values matches if the switchValue is an instanceof the class 119 | * Regular expression case value matches if the string of the switchValue matches the regex 120 | * Collection case value matches if the switchValue is contained in the collection. This also includes ranges too. 121 | * if none of the above are used then the case value matches if the case value equals the switch value 122 | 123 | The case statement performs a match on the case value using the isCase(switchValue) method, which defaults to call equals(switchValue) but has been overloaded for various types like Class or regex etc. 124 | 125 | So you could create your own kind of matcher class and add an isCase(switchValue) method to provide your own kind of matching. 126 | 127 | ### each and eachWithIndex 128 | 129 | You can use each() and eachWithIndex() in place of most loops. 130 | 131 | ``` 132 | def stringList = [ "java", "perl", "python", "ruby", "c#", "cobol"] 133 | stringList.each {print "$it "} 134 | stringList.eachWithIndex {obj, i -> println "$i: $obj"} 135 | 136 | def stringMap = [ "Su" : "Sunday", "Mo" : "Monday", "Tu" : "Tuesday"] 137 | stringMap.each {k,v -> println "$k => $v"} 138 | stringMap.eachWithIndex {obj,i -> println "$i: $obj"} 139 | ``` 140 | 141 | ### returning values from if-else and try-catch blocks 142 | 143 | Since groovy 1.6, it is possible for if/else and try/catch/finally blocks to return a value when they are the last expression in a method or a closure. No need to explicitly use the return keyword inside these constructs, as long as they are the last expression in the block of code. 144 | 145 | ``` 146 | def method() { 147 | if(true) 1 else 0 148 | } 149 | 150 | assert method()==1 151 | ``` 152 | 153 | For try/catch/finally blocks, the last expression evaluated is the one being returned. If an exception is thrown in the try block, the last expression in the catch block is returned instead. Note that finally blocks donot return any value. 154 | 155 | ``` 156 | def method(bool) { 157 | try { 158 | if(bool) throw new Exception("foo") 159 | 1 160 | } catch(e) { 161 | 2 162 | } finally { 163 | 3 164 | } 165 | } 166 | 167 | assert method(false)==1 168 | assert method(true)==2 169 | ``` 170 | 171 | ### operator overloading 172 | 173 | Groovy supports operator overloading which makes working with Numbers, Collections, Maps and various other data structures easier to use. 174 | 175 | Various operators in Groovy are mapped onto regular Java method calls on objects. This allows you to provide your own Java or Groovy objects which can take advantage of operator overloading. 176 | 177 | Operator | Method 178 | -------- | ------ 179 | a+b | a.plus(b) 180 | a-b | a.minus(b) 181 | a*b | a.multiply(b) 182 | a**b | a.power(b) 183 | a/b | a.div(b) 184 | a%b | a.mod(b) 185 | a|b | a.or(b) 186 | a&b | a.and(b) 187 | a^b | a.xor(b) 188 | a++ or ++a | a.next() 189 | a-- or --a | a.previous() 190 | a[b] | a.getAt(b) 191 | a[b]=c | a.putAt(b, c) 192 | a<>b | a.rightShift(b) 194 | switch(a){case(b):} | b.isCase(a) 195 | ~a | a.bitwiseNegate() 196 | -a | a.negative() 197 | +a | a.positive() 198 | 199 | Note that all the following comparison operators handle nulls gracefully avoiding the throwing of NullPointerException 200 | 201 | Operator | Method 202 | -------- | ------ 203 | a==b | a.equals(b) or a.compareTo(b)==0 204 | a!=b | !a.equals(b) 205 | a<=>b | a.compareTo(b) 206 | a>b | a.compareTo(b)>0 207 | a>=b | a.compareTo(b)>=0 208 | a child?.action} 222 | ``` 223 | The action may either be a method call or property access, and returns a list of the items returned from each child call. 224 | 225 | ### using invokeMethod and getProperty 226 | 227 | In any Groovy class you can override `invokeMethod` which will essentially intercept all method calls (to intercept calls to existing methods, the class additionally has to implement the `GroovyInterceptable` interface). This makes it possible to construct some quite interesting DSLs and builders. 228 | 229 | ``` 230 | class XmlBuilder { 231 | def out 232 | XmlBuilder(out) { this.out = out } 233 | def invokeMethod(String name, args) { 234 | out << "<$name>" 235 | if(args[0] instanceof Closure) { 236 | args[0].delegate = this 237 | args[0].call() 238 | } 239 | else { 240 | out << args[0].toString() 241 | } 242 | out << "" 243 | } 244 | } 245 | def xml = new XmlBuilder(new StringBuffer()) 246 | xml.html { 247 | head { 248 | title "Hello World" 249 | } 250 | body { 251 | p "Welcome!" 252 | } 253 | } 254 | println xml.out 255 | ``` 256 | You can also override property access using the `getProperty` and `setProperty` property access hooks: 257 | 258 | ``` 259 | class Expandable { 260 | def storage = [:] 261 | def getProperty(String name) { storage[name] } 262 | void setProperty(String name, value) { storage[name] = value } 263 | } 264 | 265 | def e = new Expandable() 266 | e.foo = "bar" 267 | println e.foo 268 | ``` 269 | 270 | ### Object-Related operators 271 | 272 | * java field 273 | 274 | Groovy dynamically creates getter method for all your fields that can be referenced as properties. 275 | 276 | ``` 277 | class X { 278 | def field 279 | } 280 | 281 | x = new X() 282 | x.field = 1 283 | println x.field 284 | ``` 285 | You can override these getters with your own implementations if you like. 286 | 287 | The @ operator allows you to override this behavior and access the field directly: 288 | 289 | ``` 290 | class X { 291 | def field 292 | 293 | def getField() { 294 | field + 1 295 | } 296 | } 297 | 298 | x = new X() 299 | x.field = 1 300 | println x.field // 2 301 | println x.@field // 1 302 | ``` 303 | * safe navigation operator(?.) 304 | 305 | The safe navigation operator is used to avoid a NullPointerException. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. To avoid this, the safe navigation operator will simply return `null` instead of throwing an exception: 306 | 307 | ``` 308 | def user = User.find('admin') 309 | def streetName = user?.address?.street 310 | ``` 311 | 312 | * regular expression operator 313 | 314 | Groovy supports regular expressions natively using the ~/string/ expression, which creates a compiled Java Pattern object from the given pattern string. Groovy also supports the =~ (create Matcher) and ==~ (returns boolean, whether String matches the pattern) operators. 315 | 316 | ``` 317 | import java.util.regex.Matcher 318 | import java.util.regex.Pattern 319 | 320 | def pattern = ~/\d+/ 321 | assert pattern instanceof Pattern 322 | assert "1234" ==~ pattern 323 | ``` 324 | 325 | ### classes 326 | 327 | Classes are defined in Groovy similar to Java. Methods can be class(static) or instance based and can be public, protected, private and support all the usual Java modifiers like synchronized. Package and class imports use the Java syntax. Groovy automatically imports the following: 328 | 329 | * java.lang 330 | * java.io 331 | * java.math 332 | * java.net 333 | * java.util 334 | * groovy.lang 335 | * groovy.util 336 | 337 | One difference between Java and Groovy is that by default methods are public unless you specify otherwise. Groovy also merges the idea of fields and properties together to make code simpler. Here is an example: 338 | 339 | ``` 340 | class Customer { 341 | // properties 342 | Integer id 343 | String name 344 | Date dob 345 | 346 | // sample code 347 | static void main(args) { 348 | def customer = new Customer(id:1, name:"Gromit", dob:new Date()) 349 | println("Hello ${customer.name}") 350 | } 351 | } 352 | ``` 353 | The Groovy code above is equivalent to the following Java code: 354 | 355 | ``` 356 | import java.util.Date; 357 | 358 | public class Customer { 359 | // properties 360 | private Integer id; 361 | private String name; 362 | private Date dob; 363 | 364 | public Integer getId() { 365 | return this.id; 366 | } 367 | 368 | public String getName() { 369 | return this.name; 370 | } 371 | 372 | public Date getDob() { 373 | return this.dob; 374 | } 375 | 376 | public void setId(Integer id) { 377 | this.id = id; 378 | } 379 | 380 | public void setName(String name) { 381 | this.name = name; 382 | } 383 | 384 | public void setDob(Date dob) { 385 | this.dob = dob; 386 | } 387 | 388 | // sample code 389 | public static void main(String[] args) { 390 | Customer customer = new Customer(); 391 | customer.setId(1); 392 | customer.setName("Gromit"); 393 | customer.setDob(new Date()); 394 | 395 | System.out.println("Hello " + customer.getName()); 396 | } 397 | } 398 | ``` 399 | 400 | When Groovy is compiled to bytecode, the following rules are used: 401 | 402 | * if the name is declared with an access modifier then a field is generated. 403 | * a name declared with no access modifier generates a private field with public getter and setter (i.e. a property) 404 | * if a property is declared final the private field is created final and no setter is generated 405 | * you can declare a property and also declare your own getter or setter 406 | * you can declare a property and a field of the same name, the property will use that field then 407 | * if you want a private or protected property you have to provide your own getter and setter which must be declared private or protected. 408 | * if you access a property from within the class the property is defined in at compile time with implicit or explicit this, Groovy will access the field directly instead of going though the getter and setter 409 | * if you access a property that does not exist using the explicit or implicit foo, then Groovy will access the property through the meta class, which may fail at runtime. 410 | 411 | Each class in Groovy is a Java class at the bytecode/JVM level. Any methods declared will be available to Java and vice versa. You can specify the types of parameters or return types on methods so that they work nicely in normal Java code. If you omit the types of any methods or properties they will default to java.lang.Object at the bytecode/JVM level. 412 | 413 | ### multiple assignments 414 | 415 | Groovy is able to define and assign several variables at once: 416 | 417 | ``` 418 | def geo(location) { 419 | [48.824068, 2.531733] 420 | } 421 | 422 | def (lat,lon) = geo('ShangHai') 423 | ``` 424 | 425 | And you can also define the types of variables: `def (double lat, double lon) = geo("ShangHai")` 426 | 427 | If the list on the right-hand side contains more elements than the number of variables on the left-hand side, only the first elements will be assigned in order into the variables. Also, when there are less elements than variables, the extra variables will assigned null. 428 | 429 | ### closure 430 | 431 | Closure parameters are listed before the `->` token, like so: `def printSum = {a,b -> print a+b}`. The `->` token is optional and may be omitted if your closure definition takes fewer than two parameters. A closure without `->` is a closure with one argument that is implicitly named as `it`. In some case, you need to construct a closure with zero parameters, you have to explicity define your closure as `{->}` instead of just `{}`. 432 | 433 | Closures may refer to variables not listed in their parameter list. 434 | 435 | ``` 436 | def myConst = 5 437 | def inc = {num -> num+myConst} 438 | myConst = 10 439 | println inc(20) // 30 440 | ``` 441 | 442 | Within a Groovy closure, several variables are defined that have special meaning. 443 | 444 | * it. If you have a closure that takes a single argument, you may omit the parameter definition of the closure: `def clos = {print it}; clos("hi there");` 445 | * this. as in Java, `this` refers to the instance of the enclosing class where a closure is defined 446 | * owner. the enclosing object(`this` or a surrounding closre) 447 | * delegate. by default the same as `owner`, but changeable. 448 | 449 | ``` 450 | class Class1 { 451 | def closure = { 452 | println this.class.name 453 | println delegate.class.name 454 | def nestedClos = { 455 | println owner.class.name 456 | } 457 | nestedClos() 458 | } 459 | } 460 | 461 | def clos = new Class1().closure 462 | clos.delegate = this 463 | clos() 464 | 465 | /* prints: 466 | Class1 467 | Script1 468 | Class1$_closure1 469 | */ 470 | ``` 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | -------------------------------------------------------------------------------- /java/README.md: -------------------------------------------------------------------------------- 1 | ## Java 相关的博客 2 | 3 | * [获取远程服务器上 Java 进程的运行状态](./jps.jstat.remote.md) -------------------------------------------------------------------------------- /java/jps.jstat.remote.md: -------------------------------------------------------------------------------- 1 | ## 获取远程服务器上 Java 进程的运行状态 2 | 3 | 为了安全考虑, 有些服务器会被限制登录. 本文介绍如何获取远程服务器上 Java 进程的运行状态. 4 | 5 | ### 启动 jstatd 服务 6 | 7 | 在服务器端启动 jstatd 服务后, 远程的机器可以通过 rmi 协议获取服务器上 Java 程序的运行状态. 8 | 9 | 在服务器上创建 jstatd 的授权文件, 假设文件路径为`/etc/jstatd.all.policy`, 内容如下: 10 | 11 | ``` 12 | grant codebase "file:/usr/local/java/lib/tools.jar" { 13 | permission java.security.AllPermission; 14 | }; 15 | ``` 16 | 17 | 如果你的`JAVA_HOME`目录不是`/usr/local/java`的话, 请改为正确的值. 18 | 19 | 接下来通过以下命令启动 jstatd 服务: 20 | 21 | jstatd -J-Djava.security.policy=/etc/jstatd.all.policy -p 12345 22 | 23 | 需要注意的地方有: 24 | 25 | * 授权文件的路径需要改成你自己的, 最好使用绝对路径. 26 | * `-p`参数指定 jstatd 服务监听的端口. 如果不指定的话, 默认的端口为 1009. 不过从我自己的实践来看, 最好还是设定一个比1024大的端口号. 27 | 28 | ### 远程使用jps, jstat命令 29 | 30 | 在服务器上启动 jstatd 服务之后, 就可以在自己的机器上查看服务器上运行的 Java 进程了. 假设服务器的IP为 192.168.2.37, jstatd 服务监听的端口号为 12345. 31 | 32 | 首先通过 jps 命令获取服务器上运行的 Java 进程列表: 33 | 34 | jps -l rmi://192.168.2.37:12345 35 | 36 | 拿到 Java 进程的 pid 列表之后, 可以通过 jstat 命令获取某个进程的 GC 信息: 37 | 38 | jstat -gcutil rmi://39939@192.168.2.37:12345 1000 1000 39 | 40 | 其中 39939 表示 Java 进程的pid. 41 | 42 | ### 远程使用 VisualVM 监控 Java 应用 43 | 44 | 通过VisualVM, 可以在图形面板上看到很多 Java 应用的信息, 相当于多个命令(jps, jstat, jstack, jmap, jinfo)的集合. 45 | 46 | VisualVM 是一个图形应用, 只能运行在本机, 然后通过远程连接, 获取服务器上的 Java 应用的信息. 47 | 48 | 通过 $JAVA_HOME/bin/jvisualvm 命令启动 VisualVM, 点击下图的红框部分, 输入要连接服务器的IP地址: 49 | 50 | ![alt text](./visualvm1.png "Title") 51 | 52 | 然后右键点击服务器地址, 可以看到能够通过2种方式连接服务器, 分别是 jmx 和 jstatd. 53 | 54 | ![alt text](./visualvm2.png "Title") 55 | 56 | 按照上述的步骤在服务器上启动 jstatd 服务后, 就能够以 jstatd 的形式连接到远程服务器了. 57 | 58 | VisualVM 通过 jstatd 连接的方式能够获取的信息比较有限. 如果想获取更完整的 Java 应用信息, 可以通过 jmx 的方式连接服务器上的 Java 进程. 需要在启动 Java 应用的时候, 指定以下和 jmx 相关的参数: 59 | 60 | ``` 61 | -Djava.rmi.server.hostname=10.11.2.139 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=9090 62 | ``` 63 | 64 | `java.rmi.server.hostname`参数指定ip或者host, `com.sun.management.jmxremote.port`参数指定 jmx 监听的端口. 65 | 66 | -------------------------------------------------------------------------------- /java/visualvm1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xing4git/blog/94f8d1e8d284d1b214c3a23ac96b4c510964ae61/java/visualvm1.png -------------------------------------------------------------------------------- /java/visualvm2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xing4git/blog/94f8d1e8d284d1b214c3a23ac96b4c510964ae61/java/visualvm2.png -------------------------------------------------------------------------------- /myBatis/README.md: -------------------------------------------------------------------------------- 1 | Index 2 | ----- 3 | 4 | ####一个简单的例子 5 | *2013-03-26* 6 | mybatis 是非常优秀的 ORM 框架, 相对于 JDBC, mybatis 封装了大量细节, 具有更好的编程体验; 相对于 hibernate, mybatis 更容易掌握. 下面通过一个简单的例子开始我们的 mybatis 之旅....[Read More](myBatis/一个简单的例子.md) 7 | 8 | -------------------------------------------------------------------------------- /myBatis/upload.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "flag" 7 | "fmt" 8 | "github.com/xing4git/cmdutils" 9 | "io/ioutil" 10 | "os" 11 | "regexp" 12 | "sort" 13 | ) 14 | 15 | var ( 16 | readme = bytes.NewBuffer(make([]byte, 0)) 17 | change = bytes.NewBuffer(make([]byte, 0)) 18 | commit = bytes.NewBuffer(make([]byte, 0)) 19 | ) 20 | 21 | var ( 22 | reg = regexp.MustCompile("^_\\d{4}-\\d{2}-\\d{2}-") 23 | filenames = make([]string, 0) 24 | dirname = flag.String("d", "myBatis", "current dir name") 25 | ) 26 | 27 | func init() { 28 | flag.Parse() 29 | flag.PrintDefaults() 30 | fmt.Println("current dir name: " + *dirname) 31 | } 32 | 33 | func main() { 34 | dir, err := os.Open(".") 35 | checkErr(err) 36 | defer dir.Close() 37 | 38 | fis, err := dir.Readdir(0) 39 | checkErr(err) 40 | 41 | for i := 0; i < len(fis); i++ { 42 | fi := fis[i] 43 | filename := fi.Name() 44 | if reg.Match([]byte(filename)) { 45 | filenames = append(filenames, filename) 46 | } 47 | } 48 | 49 | sort.Strings(filenames) 50 | fmt.Println("filenames: ", filenames, "\n") 51 | 52 | readme.WriteString("Index\n") 53 | readme.WriteString("-----\n\n") 54 | change.WriteString("update README.md;") 55 | 56 | for key, value := range filenames { 57 | realname := value[12:] 58 | readme.WriteString("####" + decorateFilename(realname) + "\n") 59 | 60 | file, err := os.Open(value) 61 | checkErr(err) 62 | defer file.Close() 63 | 64 | readme.WriteString("*" + value[1:11] + "*\n") 65 | buf := bufio.NewReader(file) 66 | line, err := buf.ReadString('\n') 67 | checkErr(err) 68 | readme.WriteString(string(line[0 : len(line)-1])) 69 | line, err = buf.ReadString('\n') 70 | checkErr(err) 71 | readme.WriteString(string(line[0 : len(line)-1])) 72 | readme.WriteString("...[Read More](" + *dirname + "/" + realname + ")\n\n") 73 | 74 | file.Seek(0, os.SEEK_SET) 75 | nbytes, err := ioutil.ReadAll(file) 76 | checkErr(err) 77 | var tempbuf []byte 78 | tempbuf = append(tempbuf, []byte(decorateFilename(realname)+"\n"+"----\n\n")...) 79 | nbytes = append(tempbuf, nbytes...) 80 | 81 | nbytes = append(nbytes, []byte("\n\n"+"links\n"+"-----\n")...) 82 | nbytes = append(nbytes, []byte("+ [目录](../"+*dirname+")\n")...) 83 | if key != 0 { 84 | previous := filenames[key-1][12:] 85 | nbytes = append(nbytes, []byte("+ 上一节: ["+decorateFilename(previous)+"]("+previous+")\n")...) 86 | } 87 | if key != len(filenames)-1 { 88 | next := filenames[key+1][12:] 89 | nbytes = append(nbytes, []byte("+ 下一节: ["+decorateFilename(next)+"]("+next+")\n")...) 90 | } 91 | 92 | pbytes, err := ioutil.ReadFile(realname) 93 | if err == nil && bytes.Equal(pbytes, nbytes) { 94 | fmt.Println("no change file:", realname) 95 | continue 96 | } 97 | 98 | change.WriteString("update " + realname + ";") 99 | err = ioutil.WriteFile(realname, nbytes, 0664) 100 | checkErr(err) 101 | } 102 | 103 | err = ioutil.WriteFile("README.md", readme.Bytes(), 0664) 104 | checkErr(err) 105 | 106 | commit.WriteString("git add .\n") 107 | commit.WriteString("git commit -a -m '" + change.String() + "'\n") 108 | commit.WriteString("git push -u origin master\n") 109 | fmt.Println(commit.String()) 110 | ret, err := cmdutils.BashExecute(commit.String()) 111 | checkErr(err) 112 | fmt.Println(ret) 113 | } 114 | 115 | func decorateFilename(str string) string { 116 | bytes := []byte(str) 117 | var suffixStart int = -1 118 | for i := len(str) - 1; i >= 0; i-- { 119 | if bytes[i] == '.' { 120 | suffixStart = i 121 | break 122 | } 123 | } 124 | 125 | if suffixStart != -1 { 126 | bytes = bytes[:suffixStart] 127 | } 128 | 129 | for pos, v := range bytes { 130 | if v == '-' { 131 | bytes[pos] = ' ' 132 | } 133 | } 134 | 135 | return string(bytes) 136 | } 137 | 138 | func checkErr(err error) { 139 | if err != nil { 140 | fmt.Fprintf(os.Stderr, "error: %s\n", err.Error()) 141 | os.Exit(1) 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /myBatis/一个简单的例子.md: -------------------------------------------------------------------------------- 1 | 一个简单的例子 2 | ---- 3 | 4 | mybatis 是非常优秀的 ORM 框架, 相对于 JDBC, mybatis 封装了大量细节, 具有更好的编程体验; 相对于 hibernate, mybatis 更容易掌握. 5 | 下面通过一个简单的例子开始我们的 mybatis 之旅. 6 | 7 | ### 创建数据表 8 | 以一个多用户 blog 系统为例. 为了简化问题, 首先创建2个表: post 和 user. post 表中存储文章信息, 而 user 表中存储用户信息. 9 | ```sql 10 | CREATE TABLE `user` ( 11 | `id` INT NOT NULL AUTO_INCREMENT , 12 | `name` VARCHAR(45) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL , 13 | `email` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL , 14 | PRIMARY KEY (`id`) 15 | ); 16 | 17 | CREATE TABLE `post` ( 18 | `id` INT NOT NULL AUTO_INCREMENT , 19 | `title` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL COMMENT '文章标题' , 20 | `date` INT NOT NULL COMMENT '发表日期, UNIX时间戳' , 21 | PRIMARY KEY (`id`) 22 | ); 23 | ``` 24 | 25 | ### 准备 JavaBean 26 | 创建 Post 类和 User 类, 分别对应 post 表和 user 表. 27 | ```java 28 | public class User { 29 | private Integer id; 30 | private String name; 31 | private String email; 32 | // 省略 getter, setter 方法 33 | } 34 | 35 | public class Post { 36 | private Integer id; 37 | private String name; 38 | private Integer date; 39 | // 省略 getter, setter 方法 40 | } 41 | ``` 42 | 43 | ### mybatis 核心配置文件 44 | 现在开始正式接触 mybatis, 首先将 mybatis 的 jar 包和 mysql 的驱动 jar 包加入到 classpath 中. 45 | xml 是 mybatis 支持最为全面的配置方式, 下面的 config/mybatis/configuration.xml 是 mybatis 的核心配置文件. 46 | ```xml 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | ``` 65 | 其 root 标签为 configuration, 表示 mybatis 的相关配置. environments 标签配置数据库环境, 可以在其中配置多个环境, default 属性用于指定默认使用哪个环境. environment 标签配置具体的数据库环境, 其 id 属性用于标识该环境, environments 标签的 default 属性的值必须是其中一个 environment 标签 id 属性的值. dataSource 标签配置数据库连接池. 66 | 67 | ### UserMapper 和 mapper 配置文件 68 | 在 mybatis 中, 一般会为每个数据库表编写对应的 Mapper 类, 相当于 JDBC 中的 DAO 类. 与 DAO 不同的是, Mapper 一般都是接口, 我们只需要在其中定义好数据访问的方法即可. 下面的 UserMapper 接口中仅定义了一个方法: 69 | ```java 70 | public interface UserMapper { 71 | User getById(int id); 72 | } 73 | ``` 74 | 接口定义好了, 接下来是否就是提供该接口的实现类呢? 在 mybatis 中, 使用者一般不需要提供 Mapper 接口的实现类, 而是由框架为我们提供实现类. 当然, mybatis 并不是万能的, 如果我们没有给它提供充足的信息, 它是无法为我们自动生成 Mapper 接口的实现类的. 75 | 我们可以通过 xml 文件给 mybatis 提供它所需的信息, 下面的 config/mybatis/mappers/UserMapper.xml 配置文件对应的是 UserMapper 接口. 76 | ```xml 77 | 78 | 79 | 80 | 83 | 84 | ``` 85 | mapper 标签的 namespace 属性是 UserMapper 接口的全限定名, 表明该配置文件是为 UserMapper 接口准备的. 86 | select 标签的 id 属性的值为 getById, 对应 UserMapper 接口中的 getById 方法. 其 parameterType 属性指定方法的参数为 int, 而 resultType 属性指定返回值. select 标签体中的 SQL 语句非常简单, 需要注意 SQL 语句中使用 `#{id}` 的形式引用 getById 方法的参数. mybatis 会自动将 SQL 语句的返回结果映射成 User 对象返回. 87 | 回到 config/mybatis/configuration.xml 文件, 在其中插入如下的片段: 88 | ```xml 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | ``` 97 | 有了上面的配置文件, mybatis 就知道该如何为我们生成 UserMapper 接口的实现类了. 98 | 99 | ### Java API 100 | 接下来使用 mybatis 提供的 API 调用测试 UserMapper 的 getById 方法. 101 | ```java 102 | public class Main { 103 | public static void main(String[] args) throws Exception { 104 | SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); 105 | SqlSessionFactory factory = builder.build(Resources.getResourceAsReader("config/mybatis/configuration.xml")); 106 | SqlSession session = null; 107 | try { 108 | session = factory.openSession(); 109 | UserMapper mapper = session.getMapper(UserMapper.class); 110 | User user = mapper.getById(1); 111 | 112 | System.out.println("User: id = " + user.getId() + ", name = " + user.getName() + ", email = " + user.getEmail()); 113 | } finally { 114 | if (session != null) { 115 | session.close(); 116 | } 117 | } 118 | } 119 | } 120 | ``` 121 | 通过 SqlSessionFactoryBuilder 对象的 build 方法能够得到 SqlSessionFactory 对象, 在 build 方法中需要指定核心配置文件的位置. 122 | SqlSessionFactory 是 SqlSession 的工厂类, 其 openSession 方法返回一个 SqlSession 对象. SqlSession 的 getMapper(UserMapper.class) 方法返回 mybatis 为我们自动生成的 UserMapper 的实现类的实例. 123 | 最后不能忘了在 finally 块中关闭 session, 以释放资源. 124 | 运行 main 方法, 如果 user 表中存在 id 为1的数据, 将观察到输出信息. 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | links 148 | ----- 149 | + [目录](../myBatis) 150 | -------------------------------------------------------------------------------- /scala.note.2.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xing4git/blog/94f8d1e8d284d1b214c3a23ac96b4c510964ae61/scala.note.2.md -------------------------------------------------------------------------------- /scala.note.md: -------------------------------------------------------------------------------- 1 | ``` 2 | def max(x:Int, y:Int):Int = { 3 | if(x>y) x else y 4 | } 5 | ``` 6 | 7 | Sometimes the Scala compiler will require you to specify the result type of a function. If the function is recursive, for example, you must explicitly specify the function's result type. In the case of `max` however, you may leave the result type off and the compiler will inter it. Also, if a function consists of just one statement, you can optionally leave off the curly braces. 8 | 9 | ``` 10 | def max(x:Int, y:Int) = if(x>y) x else y 11 | ``` 12 | 13 | Nevertheless, it is often a good idea to indicate function result types explicitly, even when the compiler doesnot require it. Such type annotations can make the code easier to read, because the reader need not study the function body to figure out the inferred result type. 14 | 15 | ---- 16 | Java's ++i and i++ donot work in Scala. To increment in Scala, you need to say either i=i+1 or i+=1. 17 | 18 | ---- 19 | One way to print each command line argument is: 20 | 21 | args.foreach(arg => println(arg)) 22 | 23 | In this code, you call the foreach method on args, and pass in a function. In this case, you are passing in a function literal that takes one parameter named `arg`. 24 | 25 | In the previous example, the Scala interpreter inters the type of `arg` to be String, since String is the element type of the array on which you are calling foreach. If you would prefer to be more explicit, you can mention the type name, but when you do you will need to wrap the argument portion in parentheses. 26 | 27 | args.foreach((arg: String) => println(arg)) 28 | 29 | If a function literal consists of one statement that takes a single argument, you need not explicitly name and specify the argument. 30 | 31 | args.foreach(println) 32 | 33 | To summarize, the syntax for a function literal is a list of named parameters, in parentheses, a right arrow, and then the body of the function. 34 | 35 | ---- 36 | Another way to print each command line argument is: 37 | 38 | for(arg <- args) 39 | println(arg) 40 | 41 | To the right of the <- symbol is the familiar args array. To the left <- is "arg", the name of a val, not a var. (Because it is always a val, you just write "arg" by itself, not "val arg"). Although arg may seem to be a var, because it will get a new value on each iteration, it really is a val: arg cannot be reassigned inside the body of the for expression. Instead, for each element of the args array, a new arg val will be created and initialized to the element value, and the body of the for will be executed. 42 | 43 | ---- 44 | When you define a variable with val, the variable cannot be reassigned, but the object it refers could potentially still be changed. 45 | 46 | val greets = new Array[String](3) 47 | greets(0) = "Hello" 48 | greets(1) = "," 49 | greets(2) = "World!" 50 | 51 | So in this case, you could not reassign greets to a different array, greets will always point to the same Array[String] instance with which it was initialized. But you can change the elements of the Array[String] over time, so the array itself is mutable. 52 | 53 | ---- 54 | If a method(not a function) takes only one parameter, you can call it without a dot or parentheses. 55 | 56 | 0.to(2) // equals 57 | 0 to 2 58 | 59 | Note that this syntax only works if you explicitly specify the receiver of the method call. You can not write `println 10`, but you can write `Console println 10`. 60 | 61 | --- 62 | Scala does not technically have operator overloading, because it does not actually have operators in the traditional sense. Instead, characters such as +,-,*,/ can be used in method names. Thus, when you typed `1+2`, you were actually `invoking a method named + on the Int object 1, passing in 2 as a parameter`. You could alternatively have written `1+2` using traditional method invocation syntax `(1).+(2)`. 63 | 64 | ---- 65 | In Scala, you can access an element by specifying an index in parentheses. So the first element in Scala array named args is args(0), not args[0], as in Java. 66 | 67 | In Scala, when you apply parentheses surrouding one or more values to a variable, Scala will transform the code into an invocation of a method named `apply` on that variable. So `greets(0)` gets transformed into `greets.apply(0)`. Thus accessing an element of an array in Scala is simply a method call like any other. 68 | 69 | This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an `apply` method call. Of course this will compile only if that type of object actually defines an `apply` method. So it is not a special case; it is a general rule. 70 | 71 | Similarly, when an assignment is made to a variable to which parentheses and one or more arguments have been applied, the compiler will transform that into an invocation of an `update` method that takes that arguments in parentheses as well as the object to the right of equals sign. For example, `greets(0) = "hello"` will be transformed into: `greets.update(0, "hello")`. 72 | 73 | ---- 74 | As you have seen, a Scala array is a mutable sequence of objects that all share the same type. An Array[String] contains only strings, although you can not change the length of an array after it is instantiated, you can change its element values. Thus, arrays are mutable objects. 75 | 76 | For an immutable sequence of objects that share the same type you can use scala.List class. As with arrays, a List[String] contains only strings. 77 | 78 | val numbers = List(1, 2, 3) // List.apply(1, 2, 3) 79 | 80 | You can use `::` operator to prepends a new element to the beginning of an existing list, and returns the resulting list. 81 | 82 | val numbers = List(2, 3) 83 | val oneTwoThree = 1::numbers // oneTwoThree = List(1, 2, 3) 84 | 85 | You can also use `:::` for list concatenation: 86 | 87 | val numbers = List(1, 2) ::: List(3, 4) // List(1, 2, 3, 4) 88 | 89 | Note that in the expression `1::numbers`, `::` is a method of its right operand, the `numbers`. There is a simple rule to remember: If a method is used in operator notation, such as `a*b`, the method is invoked on the left operand, unless the method name ends in a colon. If the method name ends in a colon, the method is invoked on the right operand. Therefore, in `1::numbers` the `::` method is invoked on `numbers`, passing `1`. 90 | 91 | Given that a shorthand way to specify an empty list is Nil, one way to initialize new lists is to string together elements with the `::` operator, with Nil as the last element. 92 | 93 | val numbers = 1::2::3::Nil // List(1, 2, 3) 94 | 95 | ---- 96 | Like lists, tuples are immutable, but unlike lists, tuples can contain different types of elements. 97 | 98 | var pair = (99, "Hello") 99 | println(pair._1) 100 | println(pair._2) 101 | 102 | To instantiate a new tuple that holds some objects, just place the objects in parentheses, separated by commons. Once you have a tuple instantiated, you can access its elements individually with a dot, underscore, and the `one-based` index of the element. 103 | 104 | The actual type of a tuple depends on the number of elements it contains and the types of those elements. Thus, the type of (99,"jell") is Tuple2[Int,String]; The type of ('u', 'r', "the", 1, 4, "me") is Tuple6[Char, Char, String, Int, Int, String]. 105 | 106 | --- 107 | Scala API contains a base trait for sets, and also provides two subtraits, one for mutable sets and another for immutable sets. These three traits all share the same simple name, Set. There full qualified names differ, however, because each resides in a different package. 108 | 109 | Concrete set classes in the Scala API, such as HashSet classes extend either the mutable or immutable Set trait. Thus, if you want to use a HashSet, you can choose between mutable and immutable varieties depending upon your needs. 110 | 111 | ![set继承体系](scala.note.set.png) 112 | 113 | var jetSet = Set("Boeing", "Airbus") 114 | jetSet += "Lear" 115 | println(jetSet.contains("Cessna")) 116 | 117 | To add a new element to a set, you call `+` on the set, passing in the new element. Both mutable and immutable sets offer a `+` method, but their behavior differs. Whereas a mutable set will add the element to itself, an immutable set will create and return a new set with the element added. 118 | 119 | --- 120 | As with sets, Scala provides mutable and immutable versions of Map, using a class hierarchy. 121 | 122 | import scala.collection.mutable.Map 123 | 124 | val treasureMap = Map[Int, String]() 125 | treasureMap += (1->"Go to island") 126 | treasureMap += (2->"Find big x on ground") 127 | treasureMap += (3->"Dig") 128 | println(treasureMap(2)) 129 | 130 | This `->` method, witch you can invoke on any object in a Scala program, returns a two-element tuple containing the key and value. 131 | 132 | val romanMap = Map( 133 | 1->"I", 2->"II", 3->"III" 134 | ) 135 | 136 | 137 | ---- 138 | In Scala, `public` is the default access level. 139 | 140 | Method parameters in Scala are vals, not vars. 141 | 142 | The Scala compiler treats a function defined in the procedure style, with curly braces but no equals sign, essentially the same as a function that explicitly declares its result type to be Unit: 143 | 144 | def g() { "this string gets lost" } 145 | 146 | The function `g` returns Unit. This is true no matter what the body contains, because the Scala compiler can convert any type to Unit. For example, if the last result of a method is a String, but the method result type is declared to be Unit, the String will be converted to Unit and its value lost. 147 | 148 | If you intend to return a non-Unit value without explicitly declare result type, you need to insert the equals sign before the function body: 149 | 150 | def h() = {"this String gets returned" } 151 | 152 | The function `h` returns String. 153 | 154 | <<<<<<< HEAD 155 | ----- 156 | Prefer vals, immutable objects, and methods without side effects. Reach for them first. Use vars, mutable objects, and moethods with side effects when you have a specific need and justification for them. 157 | 158 | --- 159 | The rules of semicolon inference 160 | 161 | A line ending is treated as a semicolon unless one of the following conditions is ture: 162 | 163 | * The line in question ends in a word that would not be legal as the end of a statement, such as a period or an infix operator. 164 | * The next line begins with a word that cannot start a statement. 165 | * The line ends while inside parentheses (…) or brackets […], because these cannot contain multiple statements anyway. 166 | 167 | --- 168 | Singleton objects 169 | 170 | A singleton object definition looks like a class definition, except instead of the keyword `class` you use the keyword `object`. 171 | 172 | ``` 173 | object ChecksumAccumulator { 174 | private val cache = Map[String, Int]() 175 | 176 | def calculate(s: String): Int = { 177 | if(cache.contains(s)) 178 | cache(s) 179 | else { 180 | val acc = new ChecksumAccumulator 181 | val cs = acc.calculate(s) 182 | cache += (s->cs) 183 | cs 184 | } 185 | } 186 | } 187 | ``` 188 | 189 | When a singleton object shares the same name with a class, it is called that class's `companion object`. The class is called the `companion class` of the singleton object. A class and its companion object can access each other's private members, and you must define both the class and its companion object in the same source file. 190 | 191 | If you are a Java programmer, one way to think of singleton objects is as the home for static methods. You can invoke methods on singleton objects using a similar syntax. 192 | 193 | ``` 194 | ChecksumAccumulator.calculate 195 | ``` 196 | 197 | One difference between classes and singleton objects is that singleton objects cannot take parameters, whereas classes can. Because you can't instantiate a singleton object with the new keyword, you have no way to pass parameters to it. Each singleton object is implemented as an instance of a synthetic class referenced from a static variable, so they have the same initializtion semantics as Java statics. In particular, a singleton object is initialized the first time some code accesses it. 198 | 199 | A singleton obeject that does not share the same name with a companion class is called a standalone object. You can use standalone objects for many purposes, including collecting related utility methods together, or defining an entry point to a Scala application. 200 | 201 | 202 | --- 203 | A Scala application 204 | 205 | To run a Scala program, you must supply the name of a standalone singleton object with a main method that takes one parameter, an Array[String], and has a result type of Unit. Any standalone object with a main method of the proper signature can be used as the entry point into an application. 206 | 207 | ``` 208 | object Summer { 209 | def main(args: Array[String]) { 210 | for(arg <- args) println(arg) 211 | } 212 | } 213 | ``` 214 | 215 | Scala provides a trait, scala.Application: 216 | 217 | ``` 218 | object Summer extends Application { 219 | for(arg <- args) println(arg) 220 | } 221 | ``` 222 | 223 | To use the trait, you first write `extends Application` after the name of your singleton object. Then instead of writing a main method, you place the code you would have put in the main method directly between the curly braces of the singleton object. 224 | 225 | --- 226 | Scala implicitly imports members of packages `java.lang` and `scala`, as well as the members of a singleton object named Predef, into every Scala source file. Predef, which resides in package `scala`, contains many useful methods. For example, when you say println in a Scala source file, you are actually invoking println on Predef. Predef.println turns around and invokes Console.println, which does the real work. When you say assert, you are invoking Predef.assert. 227 | 228 | 229 | --- 230 | If an integer literal ends in an L or l, it is a Long, otherwise it is an Int. 231 | 232 | If an Int literal is assigned to a variable of type Short or Byte, the literal is treated as if it were a Short or Byte type so long as the literal value is within the valid range for that type. 233 | 234 | ``` 235 | val prog = 111L // Long 236 | val tower = 11 // Int 237 | val little: Byte = 38 // Byte 238 | ``` 239 | 240 | If a floating-point literal ends in an F or f, it is a Float, otherwise it is a Double. 241 | 242 | Scala includes a special syntax for raw strings. You start and end a raw string with three double quotation marks. The interior of a raw string may contain any chars, including newlines, quotation marks, and special characters. 243 | 244 | ``` 245 | println("""|Welcome to Ultamix 3000. |Type "HELP" for help.""") 246 | ``` 247 | 248 | 249 | --- 250 | Most operators are infix operators, which mean the method to invoke sits between, the object and parameter or parameters you wish to pass to the method. Scala also has two other operator notations: prefix and postfix. In prefix notation, you put the method name before the object, for example, `-7`. In postfix notation, you put the method after the object, for example `7 toLong`. 251 | 252 | As with the infix operators, prefix operators are a shorthand way of invoking methods. In this case, however, the name of the method has "unary_" prepended to the operator character. For instance, Scala will transform the expression `-2.0` into the method invocation `(2.0).unary_-`. 253 | 254 | Postfix operators are methods that take no arguments, when they are invoked without a dot or parentheses. In Scala, you can leave off empty parentheses on method calls. The convention is that you include parentheses if the method has side effects, such as println(), but you can leave them off if the method has no side effects, such as toLowerCase invoked on a String. In this case of method that requires no arguments, you can alternatively leave off the dot and use postfix operator notation. 255 | ======= 256 | --- 257 | Prefer vals, immutable objects, and methods without side effects. Reach for them first. Use vars, mutable objects, and moethods with side effects when you have a specific need and justification for them. 258 | 259 | --- 260 | If you want to compare two objects for equality, you can use either ==, or !=. == has been carefully crafted so that you get just the equality comparison you want in most cases. First check the left side for null, and if it is not null, call the equals method. Since equals is a method, the precise comparison you get depends on the type of the left-hand argument. Since there is an automatic null check, you donot have to do the check yourself. The automatic does not look at the right-hand side, but any reasonable equals method should return false if its argument is null. 261 | >>>>>>> fa004fdc3394401077c95432c15e7df8a3cab039 262 | 263 | In Java, you can use == to compare both primitive and reference types. On primitive types, Java's == compares value equality, as in Scala. On reference types, however, Java's == compares reference equality, which means the two variables point to the same object on the JVM's heap. Scala provides a facility for comparing reference equality, as well, under the name `eq`, or `ne`. 264 | 265 | <<<<<<< HEAD 266 | ======= 267 | --- 268 | You can invoke many methods on Scala's basic types, these methods are available via implicit conversions. For each basic type, there is also a rich wrapper that provides several additional methods. 269 | 270 | --- 271 | Implicit conversions 272 | 273 | ``` 274 | class Rational(n: Int, d: Int) { 275 | require(d!=0) 276 | private val g = gcd(n.abs, d.abs) 277 | val number = n/g 278 | val denom = d/g 279 | 280 | def this(n:Int) = this(n, 1) 281 | 282 | def +(that:Rational):Rational = new Rational(number*that.denom + that.number*denom, denom*that.denom) 283 | 284 | def +(i:Int):Rational = new Rational(number+denom*i, denom) 285 | } 286 | ``` 287 | 288 | For the Rational object r, you can write r+2, but you cannot write 2+r. Because there is not an add method accepts an Rational object on the Int 2. 289 | 290 | There is a way to solve this problem in Scala: You can create an implicit conversion that automatically converts integers to rational numbers when needed: 291 | 292 | ``` 293 | implicit def intToRational(x: Int) = new Rational(x) 294 | ``` 295 | 296 | The implicit modifier in front of the method tells the compiler to apply it automatically in a number of situations. With the conversion defined, you can now write 2+r. 297 | 298 | Implicit conversions are a very powerful technique for making libraries more fleible and more convenient to use. But they can also be easily misused. 299 | 300 | --- 301 | Almost all of Scala's control structures result in some value. Programmers can use these result value to simplify their code, just as they use return values of functions. 302 | 303 | ``` 304 | val filename = if(!args.isEmpty) args(0) else "default.txt" 305 | ``` 306 | 307 | This code is slightly shorter, but its real advantage is that it uses a val instead of a var. Using a val is the functional style, and it helps you in much the same way as a final variable in Java. 308 | 309 | The while and do-while constructs are called "loops", not expressions, because they donot result in an interesting value. The type of the result is Unit. 310 | 311 | One other construct that results in the unit value, is reassignment to vars. 312 | 313 | ``` 314 | var line = "" 315 | while((line=readLine())!="") { 316 | // 317 | } 318 | ``` 319 | 320 | The code above doesnot work in Scala. Whereas in Java, assignment results in the value assigned, but in Scala assignment always results in the unit value. 321 | 322 | --- 323 | For expression 324 | 325 | The simplest thing you can do with for is to iterate through all the elements of a collection. 326 | 327 | ``` 328 | val files = (new java.io.File("/Users")).listFiles 329 | for(file <- files) println(file) 330 | ``` 331 | 332 | Sometimes you want to filter a collection down to some subset. You can do this with a for expression by adding a filter: an if clause inside the for's parentheses. 333 | 334 | ``` 335 | for(file <- files if file.getName.endsWith(".scala")) println(file) 336 | ``` 337 | 338 | You can include more filters if you want, just keep adding if clauses. 339 | 340 | You use for to iterate values and then forgotten them so far, you can also generate a value to remember for each iteration. To do so, you prefix the body of the for expression by the keyword yield. 341 | 342 | ``` 343 | def hiddens = for{ 344 | file <- files if file.getName.contains(".") 345 | } yield file 346 | ``` 347 | 348 | When the for expression completes, the result will include all the yielded values contained in a single collection. The type of the resulting collection is based on the kind of collections processed in the iteration clauses. The syntax of a for-yield expression is like this: `for clauses yield body`. The yield goes before the entire body. Even if the body is a block surrounded by curly braces, put the yield before the first curly brace, not before the last expression of the block. 349 | 350 | --- 351 | try-catch-finally 352 | 353 | In Scala, try-catch-finally results in a value. The result is that of the try clause if no exception is thrown, or the relevant catch clause if an exception is thrown and caught. If an exception is thrown but not caught, the expression has no value at all. The value computed in the finally clause, if there is one, is dropped. Usually finally clauses do some kind of clean up such as closing a file; they should not normally change the value computed in the main body or a catch clause fo the try. 354 | 355 | ``` 356 | def urlFor(path: String) = 357 | try { 358 | new URL(path) 359 | } catch { 360 | case e: MalformedURLException => new URL("http://www.scala-lang.org") 361 | } 362 | ``` 363 | 364 | --- 365 | match expression 366 | 367 | Scala's match expression lets you select from a number of alternatives, just like switch statements in other languages. 368 | 369 | ``` 370 | val firstArg = if(args.length>0) args(0) else "" 371 | 372 | firstArg match { 373 | case "salt" => println("papper") 374 | case "chips" => println("salsa") 375 | case _ => println("huh?") 376 | } 377 | ``` 378 | 379 | There are a few important differences from Java's switch statement. One is that any kind of constant, as well as other things, can be used in cases in Scala, not just the integer-type and enum constants of Java's case statements. Another difference is that there are no breaks at the end of the each alternative. Instead the break is implicit, and there is no fall through from one alternative to the next. 380 | 381 | The match expressions also result in a value. 382 | 383 | ``` 384 | val firstArg = if (!args.isEmpty) args(0) else "" 385 | val friend = 386 | firstArg match { 387 | case "salt" => "pepper" 388 | case "chips" => "salsa" 389 | case "eggs" => "bacon" 390 | case _ => "huh?" 391 | } 392 | ``` 393 | 394 | --- 395 | A funciton literal is compiled into a class that when instantiated at runtime is a function value. Thus the distinction between function literals and values is that function literals exist in the source code, whereas funciton values exist as object at runtime. 396 | 397 | ``` 398 | (x: Int) => x+1 399 | ``` 400 | 401 | The => designates that this function converts the thing on the left to the thing on the right. So, this is a function mapping any integer x to x+1. 402 | 403 | Function values are objects, so you can store them in variables if you like. They are functions too, so you can invoke them using the usual parentheses function-call notation: 404 | 405 | ``` 406 | var increase = (x: Int) => x+1 407 | increase(10) // 11 408 | increase = (x: Int) => { 409 | x+999 410 | } 411 | increase(1) // 1000 412 | ``` 413 | 414 | Scala provides a number of ways to leave out redundant information and write function literals more briefly. One way to make a function literal more brief is to leave off the parameter types. 415 | 416 | ``` 417 | val someNums = List(-11, -10, -5, 0, 5, 10) 418 | someNums.filter((x) => x>0) // List(5, 10) 419 | ``` 420 | 421 | In the previous example, the parentheses around x are unnecessary: 422 | 423 | ``` 424 | someNums.filter(x => x>0) 425 | ``` 426 | 427 | To make a function literal even more concise, you can use underscores as placeholders for one or more parameters, so long as each parameter appears only one time with the function literal. 428 | 429 | ``` 430 | someNums.filter(_>0) 431 | ``` 432 | 433 | You can think of the underscores as a "blank" in the expression that needs to be "filled in". This blank will be filled in with an argument to the function each time the function is invoked. 434 | 435 | --- 436 | Partially applied functions 437 | 438 | Scala treats `someNums.foreach(println _)` as if `someNums.foreach(x=>println(x)`. Thus the underscore in this case is not a placeholder for a single parameter. It is a placeholder for an entire parameter list. Remember that you need to leave a space between the function name and the underscore. When you use an underscore in this way, you are writing a partially applied functions. In Scala, when you invoke a function, passing in any needed arguments, you apply that function to the arguments. 439 | 440 | ``` 441 | def sum(a:Int, b:Int, c:Int) = a+b+c 442 | sum(1, 2, 3) // apply the function sum to 1, 2, 3 arguments 443 | ``` 444 | 445 | A partially applied function is an expression in which you donot supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments. 446 | 447 | ``` 448 | val a = sum _ 449 | a(1, 2, 3) // 6 450 | ``` 451 | 452 | Here is what just happened: The variable named a refers to a function value object. This function value is an instance of a class generated automatically by the Scala compiler from `sum _`, the partially applied function expression. The class generated by the compiler has an apply method that takes three arguments. The generated class's apply method takes 3 parameters because 3 is the number of arguments missing in the `sum _` expression. The Scala compiler translates the expression `a(1,2,3)` into an invocation of the function value's apply method, passing in the three arguments 1,2,3. Thus `a(1,2,3)` is a short form for: `a.apply(1,2,3)`. 453 | 454 | This apply method, defined in the class generated automatically by the compiler from expression `sum _`, simply forwards those thress missing parameters to `sum`, and returns the result. 455 | 456 | You can also express a partially applied function by supplying some but not all of the required arguments. 457 | 458 | ``` 459 | val b = sum(1, _:Int, 3) 460 | b(5) // 9 461 | ``` 462 | 463 | In this case, the middle argument is missing. Since only one parament is missing, the Scala compiler generates a new function class whose apply method takes one argument. 464 | 465 | If you are writing a partially applied function expression in which you leave off all parameters, such as `println _`, or `sum _`, you can express it more concisely by leaving off the underscore if a function is required at that point in the code: `someNums.foreach(println)`. In situations where a funciton is not required, attempting to use this form will cause a compilation error. 466 | 467 | --- 468 | Special function call forms 469 | 470 | Scala allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function. To denote a repeated parameter, place an asterisk after the type of the parameter. 471 | 472 | ``` 473 | def echo(args: String*) = for(arg<-args) println(arg) 474 | ``` 475 | 476 | Inside the function, the type of the repeated parameter is an Array of the declared type of the parameter. Nevertheless, if you have an array of the appropriate type, and you attempt to pass it as a repeated parameter, you will get a compiler error: 477 | 478 | ``` 479 | val arr = Array("1", "2") 480 | echo(arr) //ERROR 481 | ``` 482 | 483 | To accomplish this, you will need to append the array argument with a colon and an _* symbol: `echo(arr: _*)`. This notation tells the compiler to pass each element of array as its own argument to echo, rather than all of it as a single argument. 484 | 485 | Named arguments allow you to pass arguments to a function in a different order. 486 | 487 | ``` 488 | def speed(distance: Float, time: Float): Float = distance/time 489 | speed(time=10, distance=100) 490 | ``` 491 | 492 | It is also possible to mix positional and named arguments. In that case, the positional arguments come first. Named arguments are most frequentlu used in combination with default paramter values. 493 | 494 | Scala lets you specify default values for function parameters. The argument for such a parameter can optionally be omitted from a function call, in which case the corresponding argument will be filled in with the default. 495 | 496 | ``` 497 | def printTime(out: java.io.PrintStream = Console.out, divisor: Int = 1) = out.println("time = "+ System.currentTimeMillis()/divisor) 498 | printTime(out=Console.err) 499 | printTime(divisor=1000) 500 | ``` 501 | 502 | --- 503 | Tail recursion 504 | 505 | ``` 506 | def approximate(guess: Double): Double = 507 | if(isGoodEnough(guess)) guess 508 | else approximate(improve(guess)) 509 | ``` 510 | 511 | Note that the recursive call is the last thing that happens in the evaluation of function approximate's body. Functions like approximate, which call themselves as their last action, are called tail recursive. The Scala compiler detects tail recursion and replaces it with a jump back to the beginning of the funciton, after updating the function parameters with the new values. 512 | 513 | A tail-recursive function will not build a new stack frame for each call; all calls will execute in a single frame. The use of tail recursive in Scala is fairly limited. Scala only optimizes directly recursive calls back to the same function making the call. If the recursion is indirect, no optimization is possible. 514 | 515 | --- 516 | Curring function 517 | 518 | A curried function is applied to multiple argument lists, instead of just one. 519 | 520 | ``` 521 | def curriedSum(x:Int)(y:Int) = x+y 522 | curriedSum(1)(2) // 3 523 | ``` 524 | 525 | The first invocation takes a single Int parameter named x, and returns a function value for the second function. This second function takes the Int parameter y. 526 | 527 | ``` 528 | val onePlus = curriedSum(1)_ 529 | onePlus(2) // 3 530 | ``` 531 | 532 | --- 533 | In any Scala method invocation in which you are passing in exactly one argument, you can opt to use curly braces to surround the argument instead of parentheses. 534 | 535 | ``` 536 | println("hello") 537 | println { "hello" } 538 | ``` 539 | 540 | The purpose of this ablility to substitute curly braces for parentheses for passing in one argument is to enable client programmers to write function literals between curly braces. This can make a method call feel more like a control abstraction. 541 | 542 | ``` 543 | def withPrintWriter(file: File)(op: PrintWriter=>Unit) { 544 | val writer = new PrintWriter(file) 545 | try { 546 | op(writer) 547 | } finally { 548 | writer.close() 549 | } 550 | } 551 | 552 | val file = new File("data.txt") 553 | withPrintWriter(file) { 554 | writer => writer.println(new java.util.Date) 555 | } 556 | ``` 557 | 558 | --- 559 | By-name parameters 560 | 561 | What if there is no value to pass into the code between the curly braces? To help with such situation, Scala provides by-name parameters. 562 | 563 | ``` 564 | // Without using by-name parameters 565 | var assertionEnable = true; 566 | def myAssert(predicate: ()=>Boolean) = 567 | if(assertionEnable && !predicate()) throw new AssertionError 568 | ``` 569 | 570 | The definition is fine, but using it is a little bit awkward: 571 | 572 | myAssert(()=>5>3) 573 | 574 | You would really prefer to leave out the empty parameter list and => symbol in the function literal and write the code like this: 575 | 576 | myAssert(5>3) // Won't work, because missing ()=> 577 | 578 | By-name parameters exist precisely so that you can do this. To make a by-name parameter, you give the parameter a type starting with => instead of ()=>. 579 | 580 | def byNameAssert(predicate: =>Boolean) = 581 | if(assertionEnable && !predicate) throw new AssertError 582 | 583 | Now you can leave out the empty parameter in the property you want to assert. The result is that using byNameAssert looks exactly like using a built-in control structure: 584 | 585 | byNameAssert(5>3) 586 | 587 | 588 | --- 589 | Parameterless methods 590 | 591 | ``` 592 | abstract class Element { 593 | def contents: Array[String] 594 | 595 | def height: Int = contents.length 596 | 597 | def width: Int = if(height==0) return 0 else return contents(0).length 598 | } 599 | ``` 600 | 601 | Note that none of Element's three method has a parameter list, not even an empty one. Instead of: 602 | 603 | def width(): Int 604 | 605 | The method is defined without parameter: 606 | 607 | def width: Int 608 | 609 | Such parameterlesss methods are quite common in Scala. The recommended convention is to use a parameterless method whenever there are no parameters and the method accesses mutable state only by reading fields of the containing object(it doesn't change mutable state). 610 | 611 | In principle, it is possible to leave out all empty parentheses in Scala function calls. However, it is recommended to still write the empty parentheses when the invoked method represents more than a property of its receiver object. For instance, empty parentheses are appropriate if the method performs I/O, or writes reassignable vars, or reading vars other than the receiver's fields, either directly or indirectly by using mutable objects. 612 | 613 | To summarize, it is encouraged style in Scala to define methods that take no parameters and have no side effects as parameterless methods. On the other hand, you should never define a method that has side-effects without parentheses, because then invocations of the method would like a field selection. 614 | 615 | 616 | --- 617 | In Scala, fields and methods are in the same namespace. This makes it possible for a field to override a parameterless method. 618 | 619 | ``` 620 | abstract class Element { 621 | def contents: Array[String] 622 | } 623 | 624 | class ArrayElement(conts: Array[String]) extends Element { 625 | def contents: Array[String] = conts 626 | } 627 | ``` 628 | 629 | Field contents in this version of ArrayElement is a perfectly good implementation of the parameterless method contents in class Element. 630 | 631 | On the other hand, in Scala it is forbidden to define a field and method with the same name in the same class, whereas it is allowed in Java. 632 | 633 | 634 | --- 635 | 636 | ``` 637 | class ArrayElement (val contents: Array[String]) extends Element 638 | ``` 639 | 640 | Note that now the contents parameter is prefixed by val. This is a shorthand that defines at the same time a parameter and field with the same name. You can also prefix a class parameter with var, in which case the corresponding field would be reassignable. Finally, it is possible to add modifiers such as private, protected, or override to these parametric fields, just as you can do for any other class member. 641 | 642 | ``` 643 | class Cat { 644 | val dangerous = false 645 | } 646 | 647 | class Tiger( 648 | override val dangerous: Boolean, 649 | private var age: Int 650 | ) extends Cat 651 | ``` 652 | 653 | --- 654 | Invoking superclass constructors 655 | 656 | ``` 657 | class LineElement(s: String) extends ArrayElement(Array(s)) { 658 | override def width = s.length 659 | override def height = 1 660 | } 661 | ``` 662 | 663 | Since LineElement extends ArrayElement, and ArrayElement's constructor takes a parameter(an Array[String]), LineElement needs to pass an argument to the primary constructor of its superclass. To invoke a superclass constructor, you simply place the arguments you want to pass in parentheses following the name of the superclass. 664 | 665 | 666 | --- 667 | Using override modifiers 668 | 669 | Scala requires `override` for all members that override a concrete memeber in a parent class. The modifier is optional if a memeber implements an abstract memeber with same name. The modifier is forbidden if a member does not override or implement some other memeber in a base class. 670 | 671 | Sometimes when designing an inheritance hierarchy, you want to ensure that a member cannot be overridden by subclass. In Scala, as in Java, you can do this by adding a final modifier to the member. 672 | 673 | You may also at times want to ensure that an entire class not subclassed. To do this you simply declare the entire class final by adding a final modifier to the class declaration. 674 | >>>>>>> fa004fdc3394401077c95432c15e7df8a3cab039 675 | -------------------------------------------------------------------------------- /scala.note.set.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xing4git/blog/94f8d1e8d284d1b214c3a23ac96b4c510964ae61/scala.note.set.png -------------------------------------------------------------------------------- /zookeeper/README.md: -------------------------------------------------------------------------------- 1 | Index 2 | ----- 3 | 4 | ####ZooKeeper 数据模型 5 | *2013-05-17* 6 | ZooKeeper的数据结构, 与普通的文件系统极为类似. 见下图:...[Read More](zookeeper/ZooKeeper--数据模型.md) 7 | 8 | ####Zookeeper 安装和配置 9 | *2013-05-17* 10 | Zookeeper的安装和配置十分简单, 既可以配置成单机模式, 也可以配置成集群模式.下面将分别进行介绍....[Read More](zookeeper/Zookeeper--安装和配置.md) 11 | 12 | ####ZooKeeper Java API 13 | *2013-05-18* 14 | ZooKeeper提供了Java和C的binding. 本文关注Java相关的API....[Read More](zookeeper/ZooKeeper Java API.md) 15 | 16 | ####ZooKeeper示例 分布式锁 17 | *2013-05-18* 18 | ### 场景描述在分布式应用, 往往存在多个进程提供同一服务. 这些进程有可能在相同的机器上, 也有可能分布在不同的机器上. 如果这些进程共享了一些资源, 可能就需要分布式锁来锁定对这些资源的访问. ...[Read More](zookeeper/ZooKeeper示例 分布式锁.md) 19 | 20 | ####ZooKeeper示例 实时更新server列表 21 | *2013-05-18* 22 | 通过之前的3篇博文, 讲述了ZooKeeper的基础知识点. 可以看出, ZooKeeper提供的核心功能是非常简单, 且易于学习的. 可能会给人留下ZooKeeper并不强大的印象, 事实并非如此, 基于ZooKeeper的核心功能, 我们可以扩展出很多非常有意思的应用. 接下来的几篇博文, 将陆续介绍ZooKeeper的典型应用场景....[Read More](zookeeper/ZooKeeper示例 实时更新server列表.md) 23 | 24 | -------------------------------------------------------------------------------- /zookeeper/ZooKeeper Java API.md: -------------------------------------------------------------------------------- 1 | ZooKeeper Java API 2 | ---- 3 | 4 | ZooKeeper提供了Java和C的binding. 本文关注Java相关的API. 5 | 6 | ### 准备工作 7 | 拷贝ZooKeeper安装目录下的zookeeper.x.x.x.jar文件到项目的classpath路径下. 8 | 9 | ### 创建连接和回调接口 10 | 11 | 首先需要创建ZooKeeper对象, 后续的一切操作都是基于该对象进行的. 12 |
 13 | ZooKeeper(String connectString, int sessionTimeout, Watcher watcher) throws IOException
 14 | 
15 | 以下为各个参数的详细说明: 16 | + connectString. zookeeper server列表, 以逗号隔开. ZooKeeper对象初始化后, 将从server列表中选择一个server, 并尝试与其建立连接. 如果连接建立失败, 则会从列表的剩余项中选择一个server, 并再次尝试建立连接. 17 | + sessionTimeout. 指定连接的超时时间. 18 | + watcher. 事件回调接口. 19 | 20 | 注意, 创建ZooKeeper对象时, 只要对象完成初始化便立刻返回. 建立连接是以异步的形式进行的, 当连接成功建立后, 会回调watcher的process方法. 如果想要同步建立与server的连接, 需要自己进一步封装. 21 |
 22 | public class ZKConnection {
 23 | 	/**
 24 | 	 * server列表, 以逗号分割
 25 | 	 */
 26 | 	protected String hosts = "localhost:4180,localhost:4181,localhost:4182";
 27 | 	/**
 28 | 	 * 连接的超时时间, 毫秒
 29 | 	 */
 30 | 	private static final int SESSION_TIMEOUT = 5000;
 31 | 	private CountDownLatch connectedSignal = new CountDownLatch(1);
 32 | 	protected ZooKeeper zk;
 33 | 
 34 | 	/**
 35 | 	 * 连接zookeeper server
 36 | 	 */
 37 | 	public void connect() throws Exception {
 38 | 		zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new ConnWatcher());
 39 | 		// 等待连接完成
 40 | 		connectedSignal.await();
 41 | 	}
 42 | 
 43 | 	public class ConnWatcher implements Watcher {
 44 | 		public void process(WatchedEvent event) {
 45 | 			// 连接建立, 回调process接口时, 其event.getState()为KeeperState.SyncConnected
 46 | 			if (event.getState() == KeeperState.SyncConnected) {
 47 | 				// 放开闸门, wait在connect方法上的线程将被唤醒
 48 | 				connectedSignal.countDown();
 49 | 			}
 50 | 		}
 51 | 	}
 52 | }
 53 | 
54 | 55 | ### 创建znode 56 | ZooKeeper对象的create方法用于创建znode. 57 |
 58 | String create(String path, byte[] data, List acl, CreateMode createMode);
 59 | 
60 | 以下为各个参数的详细说明: 61 | + path. znode的路径. 62 | + data. 与znode关联的数据. 63 | + acl. 指定权限信息, 如果不想指定权限, 可以传入Ids.OPEN_ACL_UNSAFE. 64 | + 指定znode类型. CreateMode是一个枚举类, 从中选择一个成员传入即可. 关于znode类型的详细说明, 可参考本人的上一篇博文. 65 | 66 | ```java 67 | /** 68 | * 创建临时节点 69 | */ 70 | public void create(String nodePath, byte[] data) throws Exception { 71 | zk.create(nodePath, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); 72 | } 73 | ``` 74 | 75 | ### 获取子node列表 76 | ZooKeeper对象的getChildren方法用于获取子node列表. 77 |
 78 | List getChildren(String path, boolean watch);
 79 | 
80 | watch参数用于指定是否监听path node的子node的增加和删除事件, 以及path node本身的删除事件. 81 | 82 | ### 判断znode是否存在 83 | ZooKeeper对象的exists方法用于判断指定znode是否存在. 84 |
 85 | Stat exists(String path, boolean watch);
 86 | 
87 | watch参数用于指定是否监听path node的创建, 删除事件, 以及数据更新事件. 如果该node存在, 则返回该node的状态信息, 否则返回null. 88 | 89 | ### 获取node中关联的数据 90 | ZooKeeper对象的getData方法用于获取node关联的数据. 91 |
 92 | byte[] getData(String path, boolean watch, Stat stat);
 93 | 
94 | watch参数用于指定是否监听path node的删除事件, 以及数据更新事件, 注意, 不监听path node的创建事件, 因为如果path node不存在, 该方法将抛出KeeperException.NoNodeException异常. 95 | stat参数是个传出参数, getData方法会将path node的状态信息设置到该参数中. 96 | 97 | ### 更新node中关联的数据 98 | ZooKeeper对象的setData方法用于更新node关联的数据. 99 |
100 | Stat setData(final String path, byte data[], int version);
101 | 
102 | data为待更新的数据. 103 | version参数指定要更新的数据的版本, 如果version和真实的版本不同, 更新操作将失败. 指定version为-1则忽略版本检查. 104 | 返回path node的状态信息. 105 | 106 | ### 删除znode 107 | ZooKeeper对象的delete方法用于删除znode. 108 |
109 | void delete(final String path, int version);
110 | 
111 | version参数的作用同setData方法. 112 | 113 | ### 其余接口 114 | 请查看ZooKeeper对象的API文档. 115 | 116 | ### 需要注意的几个地方 117 | + znode中关联的数据不能超过1M. zookeeper的使命是分布式协作, 而不是数据存储. 118 | + getChildren, getData, exists方法可指定是否监听相应的事件. 而create, delete, setData方法则会触发相应的事件的发生. 119 | + 以上介绍的几个方法大多存在其异步的重载方法, 具体请查看API说明. 120 | 121 | 122 | 123 | links 124 | ----- 125 | + [目录](../zookeeper) 126 | + 上一节: [Zookeeper 安装和配置](Zookeeper--安装和配置.md) 127 | + 下一节: [ZooKeeper示例 分布式锁](ZooKeeper示例 分布式锁.md) 128 | -------------------------------------------------------------------------------- /zookeeper/ZooKeeper--数据模型.md: -------------------------------------------------------------------------------- 1 | ZooKeeper 数据模型 2 | ---- 3 | 4 | ZooKeeper的数据结构, 与普通的文件系统极为类似. 见下图: 5 | 6 | ![ZooKeeper数据结构](./model.jpg) 7 | 8 | 图片引用自[developerworks](http://www.ibm.com/developerworks/cn/opensource/os-cn-zookeeper/) 9 | 10 | 图中的每个节点称为一个znode. 每个znode由3部分组成: 11 | - stat. 此为状态信息, 描述该znode的版本, 权限等信息. 12 | - data. 与该znode关联的数据. 13 | - children. 该znode下的子节点. 14 | 15 | ### ZooKeeper命令 16 | 在深入znode的各个部分之前, 首先需要熟悉一些常用的ZooKeeper命令. 17 | 18 | 连接server 19 | ``` 20 | bin/zkCli.sh -server 10.1.39.43:4180 21 | ``` 22 | 23 | 列出指定node的子node 24 | ``` 25 | [zk: 10.1.39.43:4180(CONNECTED) 9] ls / 26 | [hello, filesync, zookeeper, xing, server, group, log] 27 | [zk: 10.1.39.43:4180(CONNECTED) 10] ls /hello 28 | [] 29 | ``` 30 | 31 | 创建znode节点, 并指定关联数据 32 | ``` 33 | create /hello world 34 | ``` 35 | 创建节点/hello, 并将字符串"world"关联到该节点中. 36 | 37 | 获取znode的数据和状态信息 38 | ``` 39 | [zk: 10.1.39.43:4180(CONNECTED) 7] get /hello 40 | world 41 | cZxid = 0x10000042c 42 | ctime = Fri May 17 17:57:33 CST 2013 43 | mZxid = 0x10000042c 44 | mtime = Fri May 17 17:57:33 CST 2013 45 | pZxid = 0x10000042c 46 | cversion = 0 47 | dataVersion = 0 48 | aclVersion = 0 49 | ephemeralOwner = 0x0 50 | dataLength = 5 51 | numChildren = 0 52 | ``` 53 | 54 | 删除znode 55 | ``` 56 | [zk: localhost:4180(CONNECTED) 13] delete /xing/item0000000001 57 | [zk: localhost:4180(CONNECTED) 14] delete /xing 58 | Node not empty: /xing 59 | ``` 60 | 使用delete命令可以删除指定znode. 当该znode拥有子znode时, 必须先删除其所有子znode, 否则操作将失败. 61 | rmr命令可用于代替delete命令, rmr是一个递归删除命令, 如果发生指定节点拥有子节点时, rmr命令会首先删除子节点. 62 | 63 | 64 | ### znode节点的状态信息 65 | 使用get命令获取指定节点的数据时, 同时也将返回该节点的状态信息, 称为Stat. 其包含如下字段: 66 | + czxid. 节点创建时的zxid. 67 | + mzxid. 节点最新一次更新发生时的zxid. 68 | + ctime. 节点创建时的时间戳. 69 | + mtime. 节点最新一次更新发生时的时间戳. 70 | + dataVersion. 节点数据的更新次数. 71 | + cversion. 其子节点的更新次数. 72 | + aclVersion. 节点ACL(授权信息)的更新次数. 73 | + ephemeralOwner. 如果该节点为ephemeral节点, ephemeralOwner值表示与该节点绑定的session id. 如果该节点不是ephemeral节点, ephemeralOwner值为0. 至于什么是ephemeral节点, 请看后面的讲述. 74 | + dataLength. 节点数据的字节数. 75 | + numChildren. 子节点个数. 76 | 77 | ### zxid 78 | znode节点的状态信息中包含czxid和mzxid, 那么什么是zxid呢? 79 | ZooKeeper状态的每一次改变, 都对应着一个递增的`Transaction id`, 该id称为zxid. 由于zxid的递增性质, 如果zxid1小于zxid2, 那么zxid1肯定先于zxid2发生. 创建任意节点, 或者更新任意节点的数据, 或者删除任意节点, 都会导致Zookeeper状态发生改变, 从而导致zxid的值增加. 80 | 81 | ### session 82 | 在client和server通信之前, 首先需要建立连接, 该连接称为session. 连接建立后, 如果发生连接超时, 授权失败, 或者显式关闭连接, 连接便处于CLOSED状态, 此时session结束. 83 | 84 | ### 节点类型 85 | 讲述节点状态的ephemeralOwner字段时, 提到过有的节点是ephemeral节点, 而有的并不是. 那么节点都具有哪些类型呢? 每种类型的节点又具有哪些特点呢? 86 | `persistent`. persistent节点不和特定的session绑定, 不会随着创建该节点的session的结束而消失, 而是一直存在, 除非该节点被显式删除. 87 | `ephemeral`. ephemeral节点是临时性的, 如果创建该节点的session结束了, 该节点就会被自动删除. ephemeral节点不能拥有子节点. 虽然ephemeral节点与创建它的session绑定, 但只要该该节点没有被删除, 其他session就可以读写该节点中关联的数据. 使用-e参数指定创建ephemeral节点. 88 | ``` 89 | [zk: localhost:4180(CONNECTED) 4] create -e /xing/ei world 90 | Created /xing/ei 91 | ``` 92 | `sequence`. 严格的说, sequence并非节点类型中的一种. sequence节点既可以是ephemeral的, 也可以是persistent的. 创建sequence节点时, ZooKeeper server会在指定的节点名称后加上一个数字序列, 该数字序列是递增的. 因此可以多次创建相同的sequence节点, 而得到不同的节点. 使用-s参数指定创建sequence节点. 93 | ``` 94 | [zk: localhost:4180(CONNECTED) 0] create -s /xing/item world 95 | Created /xing/item0000000001 96 | [zk: localhost:4180(CONNECTED) 1] create -s /xing/item world 97 | Created /xing/item0000000002 98 | [zk: localhost:4180(CONNECTED) 2] create -s /xing/item world 99 | Created /xing/item0000000003 100 | [zk: localhost:4180(CONNECTED) 3] create -s /xing/item world 101 | Created /xing/item0000000004 102 | ``` 103 | 104 | ### watch 105 | watch的意思是监听感兴趣的事件. 在命令行中, 以下几个命令可以指定是否监听相应的事件. 106 | 107 | ls命令. ls命令的第一个参数指定znode, 第二个参数如果为true, 则说明监听该znode的子节点的增减, 以及该znode本身的删除事件. 108 | ``` 109 | [zk: localhost:4180(CONNECTED) 21] ls /xing true 110 | [] 111 | [zk: localhost:4180(CONNECTED) 22] create /xing/item item000 112 | 113 | WATCHER:: 114 | 115 | WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/xing 116 | Created /xing/item 117 | ``` 118 | 119 | get命令. get命令的第一个参数指定znode, 第二个参数如果为true, 则说明监听该znode的更新和删除事件. 120 | ``` 121 | [zk: localhost:4180(CONNECTED) 39] get /xing true 122 | world 123 | cZxid = 0x100000066 124 | ctime = Fri May 17 22:30:01 CST 2013 125 | mZxid = 0x100000066 126 | mtime = Fri May 17 22:30:01 CST 2013 127 | pZxid = 0x100000066 128 | cversion = 0 129 | dataVersion = 0 130 | aclVersion = 0 131 | ephemeralOwner = 0x0 132 | dataLength = 5 133 | numChildren = 0 134 | [zk: localhost:4180(CONNECTED) 40] create /xing/item item000 135 | Created /xing/item 136 | [zk: localhost:4180(CONNECTED) 41] rmr /xing 137 | 138 | WATCHER:: 139 | 140 | WatchedEvent state:SyncConnected type:NodeDeleted path:/xing 141 | ``` 142 | 143 | stat命令. stat命令用于获取znode的状态信息. 第一个参数指定znode, 如果第二个参数为true, 则监听该node的更新和删除事件. 144 | 145 | 146 | links 147 | ----- 148 | + [目录](../zookeeper) 149 | + 下一节: [Zookeeper 安装和配置](Zookeeper--安装和配置.md) 150 | -------------------------------------------------------------------------------- /zookeeper/ZooKeeper示例 分布式锁.md: -------------------------------------------------------------------------------- 1 | ZooKeeper示例 分布式锁 2 | ---- 3 | 4 | ### 场景描述 5 | 在分布式应用, 往往存在多个进程提供同一服务. 这些进程有可能在相同的机器上, 也有可能分布在不同的机器上. 如果这些进程共享了一些资源, 可能就需要分布式锁来锁定对这些资源的访问. 6 | 本文将介绍如何利用zookeeper实现分布式锁. 7 | 8 | ### 思路 9 | 进程需要访问共享数据时, 就在"/locks"节点下创建一个sequence类型的子节点, 称为thisPath. 当thisPath在所有子节点中最小时, 说明该进程获得了锁. 进程获得锁之后, 就可以访问共享资源了. 访问完成后, 需要将thisPath删除. 锁由新的最小的子节点获得. 10 | 有了清晰的思路之后, 还需要补充一些细节. 进程如何知道thisPath是所有子节点中最小的呢? 可以在创建的时候, 通过getChildren方法获取子节点列表, 然后在列表中找到排名比thisPath前1位的节点, 称为waitPath, 然后在waitPath上注册监听, 当waitPath被删除后, 进程获得通知, 此时说明该进程获得了锁. 11 | 12 | ### 实现 13 | 以一个DistributedClient对象模拟一个进程的形式, 演示zookeeper分布式锁的实现. 14 | 15 | ```java 16 | public class DistributedClient { 17 | // 超时时间 18 | private static final int SESSION_TIMEOUT = 5000; 19 | // zookeeper server列表 20 | private String hosts = "localhost:4180,localhost:4181,localhost:4182"; 21 | private String groupNode = "locks"; 22 | private String subNode = "sub"; 23 | 24 | private ZooKeeper zk; 25 | // 当前client创建的子节点 26 | private String thisPath; 27 | // 当前client等待的子节点 28 | private String waitPath; 29 | 30 | private CountDownLatch latch = new CountDownLatch(1); 31 | 32 | /** 33 | * 连接zookeeper 34 | */ 35 | public void connectZookeeper() throws Exception { 36 | zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() { 37 | public void process(WatchedEvent event) { 38 | try { 39 | // 连接建立时, 打开latch, 唤醒wait在该latch上的线程 40 | if (event.getState() == KeeperState.SyncConnected) { 41 | latch.countDown(); 42 | } 43 | 44 | // 发生了waitPath的删除事件 45 | if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) { 46 | doSomething(); 47 | } 48 | } catch (Exception e) { 49 | e.printStackTrace(); 50 | } 51 | } 52 | }); 53 | 54 | // 等待连接建立 55 | latch.await(); 56 | 57 | // 创建子节点 58 | thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE, 59 | CreateMode.EPHEMERAL_SEQUENTIAL); 60 | 61 | // wait一小会, 让结果更清晰一些 62 | Thread.sleep(10); 63 | 64 | // 注意, 没有必要监听"/locks"的子节点的变化情况 65 | List childrenNodes = zk.getChildren("/" + groupNode, false); 66 | 67 | // 列表中只有一个子节点, 那肯定就是thisPath, 说明client获得锁 68 | if (childrenNodes.size() == 1) { 69 | doSomething(); 70 | } else { 71 | String thisNode = thisPath.substring(("/" + groupNode + "/").length()); 72 | // 排序 73 | Collections.sort(childrenNodes); 74 | int index = childrenNodes.indexOf(thisNode); 75 | if (index == -1) { 76 | // never happened 77 | } else if (index == 0) { 78 | // index == 0, 说明thisNode在列表中最小, 当前client获得锁 79 | doSomething(); 80 | } else { 81 | // 获得排名比thisPath前1位的节点 82 | this.waitPath = "/" + groupNode + "/" + childrenNodes.get(index - 1); 83 | // 在waitPath上注册监听器, 当waitPath被删除时, zookeeper会回调监听器的process方法 84 | zk.getData(waitPath, true, new Stat()); 85 | } 86 | } 87 | } 88 | 89 | /** 90 | * 共享资源的访问逻辑写在这个方法中 91 | */ 92 | private void doSomething() throws Exception { 93 | try { 94 | System.out.println("gain lock: " + thisPath); 95 | Thread.sleep(2000); 96 | // do something 97 | } finally { 98 | System.out.println("finished: " + thisPath); 99 | // 将thisPath删除, 监听thisPath的client将获得通知 100 | // 相当于释放锁 101 | zk.delete(this.thisPath, -1); 102 | } 103 | } 104 | 105 | public static void main(String[] args) throws Exception { 106 | for (int i = 0; i < 10; i++) { 107 | new Thread() { 108 | public void run() { 109 | try { 110 | DistributedClient dl = new DistributedClient(); 111 | dl.connectZookeeper(); 112 | } catch (Exception e) { 113 | e.printStackTrace(); 114 | } 115 | } 116 | }.start(); 117 | } 118 | 119 | Thread.sleep(Long.MAX_VALUE); 120 | } 121 | } 122 | ``` 123 | 124 | ### 运行 125 | 在zookeeper中创建"/locks"节点, 如果已存在, 就删除后重新创建. 126 | 运行main方法, 观察输出结果. 127 | 128 | 129 | ### 思考 130 | 思维缜密的朋友可能会想到, 上述的方案并不安全. 假设某个client在获得锁之前挂掉了, 由于client创建的节点是ephemeral类型的, 因此这个节点也会被删除, 从而导致排在这个client之后的client提前获得了锁. 此时会存在多个client同时访问共享资源. 131 | 如何解决这个问题呢? 可以在接到waitPath的删除通知的时候, 进行一次确认, 确认当前的thisPath是否真的是列表中最小的节点. 132 | ```java 133 | // 发生了waitPath的删除事件 134 | if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) { 135 | // 确认thisPath是否真的是列表中的最小节点 136 | List childrenNodes = zk.getChildren("/" + groupNode, false); 137 | String thisNode = thisPath.substring(("/" + groupNode + "/").length()); 138 | // 排序 139 | Collections.sort(childrenNodes); 140 | int index = childrenNodes.indexOf(thisNode); 141 | if (index == 0) { 142 | // 确实是最小节点 143 | doSomething(); 144 | } else { 145 | // 说明waitPath是由于出现异常而挂掉的 146 | // 更新waitPath 147 | waitPath = "/" + groupNode + "/" + childrenNodes.get(index - 1); 148 | // 重新注册监听, 并判断此时waitPath是否已删除 149 | if (zk.exists(waitPath, true) == null) { 150 | doSomething(); 151 | } 152 | } 153 | } 154 | ``` 155 | 另外, 由于thisPath和waitPath这2个成员变量会在多个线程中访问, 最好将他们声明为volatile, 以防止出现线程可见性问题. 156 | 157 | ### 另一种思路 158 | 下面介绍一种更简单, 但是不怎么推荐的解决方案. 159 | 每个client在getChildren的时候, 注册监听子节点的变化. 当子节点的变化通知到来时, 再一次通过getChildren获取子节点列表, 判断thisPath是否是列表中的最小节点, 如果是, 则执行资源访问逻辑. 160 | ```java 161 | public class DistributedClient2 { 162 | // 超时时间 163 | private static final int SESSION_TIMEOUT = 5000; 164 | // zookeeper server列表 165 | private String hosts = "localhost:4180,localhost:4181,localhost:4182"; 166 | private String groupNode = "locks"; 167 | private String subNode = "sub"; 168 | 169 | private ZooKeeper zk; 170 | // 当前client创建的子节点 171 | private volatile String thisPath; 172 | 173 | private CountDownLatch latch = new CountDownLatch(1); 174 | 175 | /** 176 | * 连接zookeeper 177 | */ 178 | public void connectZookeeper() throws Exception { 179 | zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() { 180 | public void process(WatchedEvent event) { 181 | try { 182 | // 连接建立时, 打开latch, 唤醒wait在该latch上的线程 183 | if (event.getState() == KeeperState.SyncConnected) { 184 | latch.countDown(); 185 | } 186 | 187 | // 子节点发生变化 188 | if (event.getType() == EventType.NodeChildrenChanged && event.getPath().equals("/" + groupNode)) { 189 | // thisPath是否是列表中的最小节点 190 | List childrenNodes = zk.getChildren("/" + groupNode, true); 191 | String thisNode = thisPath.substring(("/" + groupNode + "/").length()); 192 | // 排序 193 | Collections.sort(childrenNodes); 194 | if (childrenNodes.indexOf(thisNode) == 0) { 195 | doSomething(); 196 | } 197 | } 198 | } catch (Exception e) { 199 | e.printStackTrace(); 200 | } 201 | } 202 | }); 203 | 204 | // 等待连接建立 205 | latch.await(); 206 | 207 | // 创建子节点 208 | thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE, 209 | CreateMode.EPHEMERAL_SEQUENTIAL); 210 | 211 | // wait一小会, 让结果更清晰一些 212 | Thread.sleep(10); 213 | 214 | // 监听子节点的变化 215 | List childrenNodes = zk.getChildren("/" + groupNode, true); 216 | 217 | // 列表中只有一个子节点, 那肯定就是thisPath, 说明client获得锁 218 | if (childrenNodes.size() == 1) { 219 | doSomething(); 220 | } 221 | } 222 | 223 | /** 224 | * 共享资源的访问逻辑写在这个方法中 225 | */ 226 | private void doSomething() throws Exception { 227 | try { 228 | System.out.println("gain lock: " + thisPath); 229 | Thread.sleep(2000); 230 | // do something 231 | } finally { 232 | System.out.println("finished: " + thisPath); 233 | // 将thisPath删除, 监听thisPath的client将获得通知 234 | // 相当于释放锁 235 | zk.delete(this.thisPath, -1); 236 | } 237 | } 238 | 239 | public static void main(String[] args) throws Exception { 240 | for (int i = 0; i < 10; i++) { 241 | new Thread() { 242 | public void run() { 243 | try { 244 | DistributedClient2 dl = new DistributedClient2(); 245 | dl.connectZookeeper(); 246 | } catch (Exception e) { 247 | e.printStackTrace(); 248 | } 249 | } 250 | }.start(); 251 | } 252 | 253 | Thread.sleep(Long.MAX_VALUE); 254 | } 255 | } 256 | ``` 257 | 为什么不推荐这个方案呢? 是因为每次子节点的增加和删除都要广播给所有client, client数量不多时还看不出问题. 如果存在很多client, 那么就可能导致广播风暴--过多的广播通知阻塞了网络. 使用第一个方案, 会使得通知的数量大大下降. 当然第一个方案更复杂一些, 复杂的方案同时也意味着更容易引进bug. 258 | 259 | 260 | links 261 | ----- 262 | + [目录](../zookeeper) 263 | + 上一节: [ZooKeeper Java API](ZooKeeper Java API.md) 264 | + 下一节: [ZooKeeper示例 实时更新server列表](ZooKeeper示例 实时更新server列表.md) 265 | -------------------------------------------------------------------------------- /zookeeper/ZooKeeper示例 实时更新server列表.md: -------------------------------------------------------------------------------- 1 | ZooKeeper示例 实时更新server列表 2 | ---- 3 | 4 | 通过之前的3篇博文, 讲述了ZooKeeper的基础知识点. 可以看出, ZooKeeper提供的核心功能是非常简单, 且易于学习的. 可能会给人留下ZooKeeper并不强大的印象, 事实并非如此, 基于ZooKeeper的核心功能, 我们可以扩展出很多非常有意思的应用. 接下来的几篇博文, 将陆续介绍ZooKeeper的典型应用场景. 5 | 6 | ### 场景描述 7 | 在分布式应用中, 我们经常同时启动多个server, 调用方(client)选择其中之一发起请求. 8 | 分布式应用必须考虑高可用性和可扩展性: server的应用进程可能会崩溃, 或者server本身也可能会宕机. 当server不够时, 也有可能增加server的数量. 总而言之, server列表并非一成不变, 而是一直处于动态的增减中. 9 | 那么client如何才能实时的更新server列表呢? 解决的方案很多, 本文将讲述利用ZooKeeper的解决方案. 10 | 11 | ### 思路 12 | 启动server时, 在zookeeper的某个znode(假设为/sgroup)下创建一个子节点. 所创建的子节点的类型应该为ephemeral, 这样一来, 如果server进程崩溃, 或者server宕机, 与zookeeper连接的session就结束了, 那么其所创建的子节点会被zookeeper自动删除. 当崩溃的server恢复后, 或者新增server时, 同样需要在/sgroup节点下创建新的子节点. 13 | 对于client, 只需注册/sgroup子节点的监听, 当/sgroup下的子节点增加或减少时, zookeeper会通知client, 此时client更新server列表. 14 | 15 | ### 实现AppServer 16 | AppServer的逻辑非常简单, 只须在启动时, 在zookeeper的"/sgroup"节点下新增一个子节点即可. 17 | ```java 18 | public class AppServer { 19 | private String groupNode = "sgroup"; 20 | private String subNode = "sub"; 21 | 22 | /** 23 | * 连接zookeeper 24 | * @param address server的地址 25 | */ 26 | public void connectZookeeper(String address) throws Exception { 27 | ZooKeeper zk = new ZooKeeper("localhost:4180,localhost:4181,localhost:4182", 5000, new Watcher() { 28 | public void process(WatchedEvent event) { 29 | // 不做处理 30 | } 31 | }); 32 | // 在"/sgroup"下创建子节点 33 | // 子节点的类型设置为EPHEMERAL_SEQUENTIAL, 表明这是一个临时节点, 且在子节点的名称后面加上一串数字后缀 34 | // 将server的地址数据关联到新创建的子节点上 35 | String createdPath = zk.create("/" + groupNode + "/" + subNode, address.getBytes("utf-8"), 36 | Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); 37 | System.out.println("create: " + createdPath); 38 | } 39 | 40 | /** 41 | * server的工作逻辑写在这个方法中 42 | * 此处不做任何处理, 只让server sleep 43 | */ 44 | public void handle() throws InterruptedException { 45 | Thread.sleep(Long.MAX_VALUE); 46 | } 47 | 48 | public static void main(String[] args) throws Exception { 49 | // 在参数中指定server的地址 50 | if (args.length == 0) { 51 | System.err.println("The first argument must be server address"); 52 | System.exit(1); 53 | } 54 | 55 | AppServer as = new AppServer(); 56 | as.connectZookeeper(args[0]); 57 | 58 | as.handle(); 59 | } 60 | } 61 | ``` 62 | 将其打成appserver.jar后待用, 生成jar时别忘了指定入口函数. 具体的教程请自行搜索. 63 | 64 | ### 实现AppClient 65 | AppClient的逻辑比AppServer稍微复杂一些, 需要监听"/sgroup"下子节点的变化事件, 当事件发生时, 需要更新server列表. 66 | 注册监听"/sgroup"下子节点的变化事件, 可在getChildren方法中完成. 当zookeeper回调监听器的process方法时, 判断该事件是否是"/sgroup"下子节点的变化事件, 如果是, 则调用更新逻辑, 并再次注册该事件的监听. 67 | ```java 68 | public class AppClient { 69 | private String groupNode = "sgroup"; 70 | private ZooKeeper zk; 71 | private Stat stat = new Stat(); 72 | private volatile List serverList; 73 | 74 | /** 75 | * 连接zookeeper 76 | */ 77 | public void connectZookeeper() throws Exception { 78 | zk = new ZooKeeper("localhost:4180,localhost:4181,localhost:4182", 5000, new Watcher() { 79 | public void process(WatchedEvent event) { 80 | // 如果发生了"/sgroup"节点下的子节点变化事件, 更新server列表, 并重新注册监听 81 | if (event.getType() == EventType.NodeChildrenChanged 82 | && ("/" + groupNode).equals(event.getPath())) { 83 | try { 84 | updateServerList(); 85 | } catch (Exception e) { 86 | e.printStackTrace(); 87 | } 88 | } 89 | } 90 | }); 91 | 92 | updateServerList(); 93 | } 94 | 95 | /** 96 | * 更新server列表 97 | */ 98 | private void updateServerList() throws Exception { 99 | List newServerList = new ArrayList(); 100 | 101 | // 获取并监听groupNode的子节点变化 102 | // watch参数为true, 表示监听子节点变化事件. 103 | // 每次都需要重新注册监听, 因为一次注册, 只能监听一次事件, 如果还想继续保持监听, 必须重新注册 104 | List subList = zk.getChildren("/" + groupNode, true); 105 | for (String subNode : subList) { 106 | // 获取每个子节点下关联的server地址 107 | byte[] data = zk.getData("/" + groupNode + "/" + subNode, false, stat); 108 | newServerList.add(new String(data, "utf-8")); 109 | } 110 | 111 | // 替换server列表 112 | serverList = newServerList; 113 | 114 | System.out.println("server list updated: " + serverList); 115 | } 116 | 117 | /** 118 | * client的工作逻辑写在这个方法中 119 | * 此处不做任何处理, 只让client sleep 120 | */ 121 | public void handle() throws InterruptedException { 122 | Thread.sleep(Long.MAX_VALUE); 123 | } 124 | 125 | public static void main(String[] args) throws Exception { 126 | AppClient ac = new AppClient(); 127 | ac.connectZookeeper(); 128 | 129 | ac.handle(); 130 | } 131 | } 132 | ``` 133 | 将其打包成appclient.jar后待用, 别忘了指定入口函数. 134 | 135 | ### 运行 136 | 在运行jar包之前, 需要确认zookeeper中是否已经存在"/sgroup"节点了, 没有不存在, 则创建该节点. 如果存在, 最好先将其删除, 然后再重新创建. ZooKeeper的相关命令可参考我的另一篇博文. 137 | 运行appclient.jar: `java -jar appclient.jar` 138 | 开启多个命令行窗口, 每个窗口运行appserver.jar进程: `java -jar appserver.jar server0000`. "server0000"表示server的地址, 别忘了给每个server设定一个不同的地址. 观察appclient的输出. 139 | 依次结束appserver的进程, 观察appclient的输出. 140 | appclient的输出类似于: 141 | ```bash 142 | server list updated: [] 143 | server list updated: [server0000] 144 | server list updated: [server0000, server0001] 145 | server list updated: [server0000, server0001, server0002] 146 | server list updated: [server0000, server0001, server0002, server0003] 147 | server list updated: [server0000, server0001, server0002] 148 | server list updated: [server0000, server0001] 149 | server list updated: [server0000] 150 | server list updated: [] 151 | ``` 152 | 153 | 154 | links 155 | ----- 156 | + [目录](../zookeeper) 157 | + 上一节: [ZooKeeper示例 分布式锁](ZooKeeper示例 分布式锁.md) 158 | -------------------------------------------------------------------------------- /zookeeper/Zookeeper--安装和配置.md: -------------------------------------------------------------------------------- 1 | Zookeeper 安装和配置 2 | ---- 3 | 4 | Zookeeper的安装和配置十分简单, 既可以配置成单机模式, 也可以配置成集群模式. 5 | 下面将分别进行介绍. 6 | 7 | ### 单机模式 8 | [点击这里](http://zookeeper.apache.org/releases.html)下载zookeeper的安装包之后, 解压到合适目录. 9 | 进入zookeeper目录下的conf子目录, 创建zoo.cfg: 10 | ``` 11 | tickTime=2000 12 | dataDir=/Users/apple/zookeeper/data 13 | dataLogDir=/Users/apple/zookeeper/logs 14 | clientPort=4180 15 | ``` 16 | 参数说明: 17 | + tickTime: zookeeper中使用的基本时间单位, 毫秒值. 18 | + dataDir: 数据目录. 可以是任意目录. 19 | + dataLogDir: log目录, 同样可以是任意目录. 如果没有设置该参数, 将使用和dataDir相同的设置. 20 | + clientPort: 监听client连接的端口号. 21 | 22 | 至此, zookeeper的单机模式已经配置好了. 启动server只需运行脚本: 23 | ``` 24 | bin/zkServer.sh start 25 | ``` 26 | Server启动之后, 就可以启动client连接server了, 执行脚本: 27 | ``` 28 | bin/zkCli.sh -server localhost:4180 29 | ``` 30 | 31 | ### 伪集群模式 32 | 所谓伪集群, 是指在单台机器中启动多个zookeeper进程, 并组成一个集群. 以启动3个zookeeper进程为例. 33 | 34 | 将zookeeper的目录拷贝2份: 35 | ``` 36 | |--zookeeper0 37 | |--zookeeper1 38 | |--zookeeper2 39 | ``` 40 | 41 | 更改zookeeper0/conf/zoo.cfg文件为: 42 | ``` 43 | tickTime=2000 44 | initLimit=5 45 | syncLimit=2 46 | dataDir=/Users/apple/zookeeper0/data 47 | dataLogDir=/Users/apple/zookeeper0/logs 48 | clientPort=4180 49 | server.0=127.0.0.1:8880:7770 50 | server.1=127.0.0.1:8881:7771 51 | server.2=127.0.0.1:8882:7772 52 | ``` 53 | 新增了几个参数, 其含义如下: 54 | + initLimit: zookeeper集群中的包含多台server, 其中一台为leader, 集群中其余的server为follower. initLimit参数配置初始化连接时, follower和leader之间的最长心跳时间. 此时该参数设置为5, 说明时间限制为5倍tickTime, 即5*2000=10000ms=10s. 55 | + syncLimit: 该参数配置leader和follower之间发送消息, 请求和应答的最大时间长度. 此时该参数设置为2, 说明时间限制为2倍tickTime, 即4000ms. 56 | + server.X=A:B:C 其中X是一个数字, 表示这是第几号server. A是该server所在的IP地址. B配置该server和集群中的leader交换消息所使用的端口. C配置选举leader时所使用的端口. 由于配置的是伪集群模式, 所以各个server的B, C参数必须不同. 57 | 58 | 参照zookeeper0/conf/zoo.cfg, 配置zookeeper1/conf/zoo.cfg, 和zookeeper2/conf/zoo.cfg文件. 只需更改dataDir, dataLogDir, clientPort参数即可. 59 | 60 | 在之前设置的dataDir中新建myid文件, 写入一个数字, 该数字表示这是第几号server. 该数字必须和zoo.cfg文件中的server.X中的X一一对应. 61 | /Users/apple/zookeeper0/data/myid文件中写入0, /Users/apple/zookeeper1/data/myid文件中写入1, /Users/apple/zookeeper2/data/myid文件中写入2. 62 | 63 | 分别进入/Users/apple/zookeeper0/bin, /Users/apple/zookeeper1/bin, /Users/apple/zookeeper2/bin三个目录, 启动server. 64 | 任意选择一个server目录, 启动客户端: 65 | ``` 66 | bin/zkCli.sh -server localhost:4180 67 | ``` 68 | 69 | ### 集群模式 70 | 集群模式的配置和伪集群基本一致. 71 | 由于集群模式下, 各server部署在不同的机器上, 因此各server的conf/zoo.cfg文件可以完全一样. 72 | 下面是一个示例: 73 | ``` 74 | tickTime=2000 75 | initLimit=5 76 | syncLimit=2 77 | dataDir=/home/zookeeper/data 78 | dataLogDir=/home/zookeeper/logs 79 | clientPort=4180 80 | server.43=10.1.39.43:2888:3888 81 | server.47=10.1.39.47:2888:3888 82 | server.48=10.1.39.48:2888:3888 83 | ``` 84 | 示例中部署了3台zookeeper server, 分别部署在10.1.39.43, 10.1.39.47, 10.1.39.48上. 85 | 需要注意的是, 各server的dataDir目录下的myid文件中的数字必须不同. 86 | 10.1.39.43 server的myid为43, 10.1.39.47 server的myid为47, 10.1.39.48 server的myid为48. 87 | 88 | 89 | 90 | links 91 | ----- 92 | + [目录](../zookeeper) 93 | + 上一节: [ZooKeeper 数据模型](ZooKeeper--数据模型.md) 94 | + 下一节: [ZooKeeper Java API](ZooKeeper Java API.md) 95 | -------------------------------------------------------------------------------- /zookeeper/get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xing4git/blog/94f8d1e8d284d1b214c3a23ac96b4c510964ae61/zookeeper/get.png -------------------------------------------------------------------------------- /zookeeper/ls.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xing4git/blog/94f8d1e8d284d1b214c3a23ac96b4c510964ae61/zookeeper/ls.png -------------------------------------------------------------------------------- /zookeeper/model.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xing4git/blog/94f8d1e8d284d1b214c3a23ac96b4c510964ae61/zookeeper/model.jpg -------------------------------------------------------------------------------- /zookeeper/upload.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "flag" 7 | "fmt" 8 | "github.com/xing4git/cmdutils" 9 | "io/ioutil" 10 | "os" 11 | "regexp" 12 | "runtime/debug" 13 | "sort" 14 | ) 15 | 16 | var ( 17 | readme = bytes.NewBuffer(make([]byte, 0)) 18 | change = bytes.NewBuffer(make([]byte, 0)) 19 | commit = bytes.NewBuffer(make([]byte, 0)) 20 | ) 21 | 22 | var ( 23 | reg = regexp.MustCompile("^_\\d{4}-\\d{2}-\\d{2}-") 24 | filenames = make([]string, 0) 25 | dirname = flag.String("d", "zookeeper", "current dir name") 26 | ) 27 | 28 | func init() { 29 | flag.Parse() 30 | flag.PrintDefaults() 31 | fmt.Println("current dir name: " + *dirname) 32 | } 33 | 34 | func main() { 35 | dir, err := os.Open(".") 36 | checkErr(err) 37 | defer dir.Close() 38 | 39 | fis, err := dir.Readdir(0) 40 | checkErr(err) 41 | 42 | for i := 0; i < len(fis); i++ { 43 | fi := fis[i] 44 | filename := fi.Name() 45 | if reg.Match([]byte(filename)) { 46 | filenames = append(filenames, filename) 47 | } 48 | } 49 | 50 | sort.Strings(filenames) 51 | fmt.Println("filenames: ", filenames, "\n") 52 | 53 | readme.WriteString("Index\n") 54 | readme.WriteString("-----\n\n") 55 | change.WriteString("update README.md;") 56 | 57 | for key, value := range filenames { 58 | realname := value[12:] 59 | readme.WriteString("####" + decorateFilename(realname) + "\n") 60 | 61 | file, err := os.Open(value) 62 | checkErr(err) 63 | defer file.Close() 64 | 65 | readme.WriteString("*" + value[1:11] + "*\n") 66 | buf := bufio.NewReader(file) 67 | line, err := buf.ReadString('\n') 68 | checkErr(err) 69 | readme.WriteString(string(line[0 : len(line)-1])) 70 | line, err = buf.ReadString('\n') 71 | checkErr(err) 72 | readme.WriteString(string(line[0 : len(line)-1])) 73 | readme.WriteString("...[Read More](" + *dirname + "/" + realname + ")\n\n") 74 | 75 | file.Seek(0, os.SEEK_SET) 76 | nbytes, err := ioutil.ReadAll(file) 77 | checkErr(err) 78 | var tempbuf []byte 79 | tempbuf = append(tempbuf, []byte(decorateFilename(realname)+"\n"+"----\n\n")...) 80 | nbytes = append(tempbuf, nbytes...) 81 | 82 | nbytes = append(nbytes, []byte("\n\n"+"links\n"+"-----\n")...) 83 | nbytes = append(nbytes, []byte("+ [目录](../"+*dirname+")\n")...) 84 | if key != 0 { 85 | previous := filenames[key-1][12:] 86 | nbytes = append(nbytes, []byte("+ 上一节: ["+decorateFilename(previous)+"]("+previous+")\n")...) 87 | } 88 | if key != len(filenames)-1 { 89 | next := filenames[key+1][12:] 90 | nbytes = append(nbytes, []byte("+ 下一节: ["+decorateFilename(next)+"]("+next+")\n")...) 91 | } 92 | 93 | pbytes, err := ioutil.ReadFile(realname) 94 | if err == nil && bytes.Equal(pbytes, nbytes) { 95 | fmt.Println("no change file:", realname) 96 | continue 97 | } 98 | 99 | change.WriteString("update " + realname + ";") 100 | err = ioutil.WriteFile(realname, nbytes, 0664) 101 | checkErr(err) 102 | } 103 | 104 | err = ioutil.WriteFile("README.md", readme.Bytes(), 0664) 105 | checkErr(err) 106 | 107 | commit.WriteString("git add .\n") 108 | commit.WriteString("git commit -a -m '" + change.String() + "'\n") 109 | commit.WriteString("git push -u origin master\n") 110 | fmt.Println(commit.String()) 111 | ret, err := cmdutils.BashExecute(commit.String()) 112 | checkErr(err) 113 | fmt.Println(ret) 114 | } 115 | 116 | func decorateFilename(str string) string { 117 | bytes := []byte(str) 118 | var suffixStart int = -1 119 | for i := len(str) - 1; i >= 0; i-- { 120 | if bytes[i] == '.' { 121 | suffixStart = i 122 | break 123 | } 124 | } 125 | 126 | if suffixStart != -1 { 127 | bytes = bytes[:suffixStart] 128 | } 129 | 130 | for pos, v := range bytes { 131 | if v == '-' { 132 | bytes[pos] = ' ' 133 | } 134 | } 135 | 136 | return string(bytes) 137 | } 138 | 139 | func checkErr(err error) { 140 | if err != nil { 141 | fmt.Fprintf(os.Stderr, "error: %s\n", err.Error()) 142 | debug.PrintStack() 143 | os.Exit(1) 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /在hadoop中引入LZO.md: -------------------------------------------------------------------------------- 1 | ### LZO安装和配置 2 | 3 | 我们的日志存储在hdfs上, 考虑到hdfs磁盘空间不足, 决定引入LZO压缩. 由于LZO的GPL开源协议和Hadoop采用的开源协议不兼容, 所以只能自己安装LZO. 我们的环境如下: 4 | 5 | ``` 6 | OS: CentOS release 6.5 7 | Hadoop: 2.3.0-cdh5.0.1 8 | ``` 9 | 10 | * 在hadoop集群的机器上增加yum源(/etc/yum.repos.d/文件夹下任意一个文件): 11 | 12 | ``` 13 | [cloudera-gplextras5] 14 | name=Cloudera's GPLExtras, Version 5 15 | baseurl=http://archive.cloudera.com/gplextras5/redhat/5/x86_64/gplextras/5/ 16 | gpgkey = http://archive.cloudera.com/gplextras5/redhat/5/x86_64/gplextras/RPM-GPG-KEY-cloudera 17 | gpgcheck = 1 18 | 19 | ``` 20 | 21 | * 在hadoop集群上安装lzo: 22 | 23 | ``` 24 | yum install hadoop-lzo 25 | ``` 26 | 27 | * 修改core-site.xml: 28 | 29 | ``` 30 | 31 | io.compression.codecs 32 | com.hadoop.compression.lzo.LzoCodec,com.hadoop.compression.lzo.LzopCodec 33 | 34 | ``` 35 | 在value中增加`com.hadoop.compression.lzo.LzoCodec,com.hadoop.compression.lzo.LzopCodec`, 原有的codecs依旧保留. 36 | 37 | 38 | * 重启hadoop集群 39 | 40 | * git clone https://github.com/twitter/hadoop-lzo, 修改pom文件, 更改私服地址. 执行`mvn deploy`命令, 将jar包update到私服. 之所以要upload, 是因为外部可下载的jar包不包含native代码. 41 | 42 | 43 | * 用户工程依赖私服上的lzo jar包. 代码如下: 44 | 45 | ``` 46 | Configuration conf = new Configuration(); 47 | conf.set("io.compression.codecs", "com.hadoop.compression.lzo.LzoCodec,com.hadoop.compression.lzo.LzopCodec"); 48 | CompressionCodecFactory ccf = new CompressionCodecFactory(conf); 49 | CompressionCodec codec = ccf.getCodecByName(LzopCodec.class.getName()); 50 | // codec.createInputStream() 51 | // codec.createOutputStream() 52 | ``` 53 | 使用此方法可以避免native依赖找不到的问题, 因为LZO的native依赖已经在上一步打成的包里了. 外部可下载的hadoop-lzo都是不包含native依赖的, 需要在程序运行的机器上安装了LZO, 并指定hadoop lzo的native依赖路径. 这是完全无法接受的, 因为hdfs相关的程序会部署在很多台机器上, 而且迁移变更的几率比较高, 要求运行hdfs相关程序的机器都安装lzo是不可能的. --------------------------------------------------------------------------------