Wednesday, March 11, 2015

Gnuplot Tips (1)



GNUPLOT Tips 1

For people who work under Linux, if you often have to draw some simple two-dimensional drawings and three-dimensional figure, then, gnuplot is undoubtedly a very good choice, not only the beautiful graphics, and easy to operate. However, if you need higher-quality three-dimensional figure, please use a number of other professional graphics software. Suggest that you learn to use gnuplot. This small software is usually Redhat Linux comes, but comes with version 3.7, it is recommended to upgrade to 4.0, the new version has many new features. The latest version can go to http://www.gnuplot.info/

Some of the most basic operation please read the instructions. I just summarized the problems and solutions when I using gnuplot to help those who previously could not or unskilled user to get a quick start. This brief summary cannot cover everything, so please do not complain about it. I believe that after reading it, the answer of the most common problems can be found here. If everyone has some skills or experiences that not include in here, or have other suggestions, please leave me a comment to help me improve this summary, thank you!
Also, this book is helpful if you want to know more about gnuplot.
Gnuplot in Action: Understanding Data with Graphs

1.    Basics:

In the Linux command prompt, type gnuplot to start, type quit or exit to exit.

1.1. Drawing single curve

1.1.1. 
gnuplot> plot sin(x) #all options are the default values.

1.1.2. 
gnuplot> plot sin(x) with line linetype 3 linewidth 2
OR
gnuplot> plot sin(x) w l lt 3 lw 2 #using line to draw, line types (including types of color and dotted line) is 3, the line width is 2, drawing function sin (x)

1.1.3. 
gnuplot> plot sin(x) with point pointtype 3 pointsize 2
OR
gnuplot> plot sin(x) w p pt 3 ps 2 #using point to draw, point type (including color and point type) is 3, the point size is 2, drawing function sin (x)

1.1.4. 
gnuplot> plot sin (x) title 'f (x)' w lp lt 3 lw 2 pt 3 ps 2 #using both point and line to draw, the title 'f (x)' is superscript if ignore then use the default options

1.1.5. 
gnuplot> plot 'a.dat' u 2:3 wl lt 3 lw 2 #using the second and third columns of data file a.dat to draw
By the way, from 1.1.2 and 1.1.3, in gnuplot, commands have short form such as with can be replaced by w, pointtype can be replaced by pt.

1.2. Drawing multiple curves

gnuplot> plot sin(x) title 'sin (x)' wl lt 1 lw 2, cos(x) title 'cos(x)' wl lt 2 lw 2 #two curves are separated by a comma. Draw a number of curves, each curve are separated by commas.

In the example above is drawing a function, if drawing data file, just replace the function name to the data file name, but use single quotation marks like ‘a.dat’.

1.3. Location of the legend

The default location is on the upper right.

gnuplot> set key left #on the left, there are two options left and right
gnuplot> set key bottom #on the bottom, the only option; default is on the top
gnuplot> set key outside #make it outside, but only can set it outside of the right

These three options can be combined. Such as:
gnuplot> set key left bottom #means left bottom

You can also using coordinates to represent the location of the legend accurately, such as:
gnuplot> set key 0.5,0.6 #will position the legend on the 0.5,0.6

1.4. About the axis

gnuplot> set xlabel 'x' #x-axis labeled 'x'
gnuplot> set ylabel 'y' #y-axis labeled as 'y'
gnuplot> set ylabel 'DOS' tc lt 3 #tc lt 3 means the third color of 'DOS'
gnuplot> set xtics 1.0 #set the width of the main scale of x-axis to 1.0, the same as the y-axis can be defined by ytics
gnuplot> set mxtics 3 #separate main scale of x-axis into 3 parts , the same as the y-axis can be defined mytics
gnuplot> set border 3 lt 3 lw 2 #is set the border to the third type, color type is 3, line width is 2

The same things can be done to the top x-axis (called x2) and the right of the y-axis (called y2) axis, using x2tics, mx2tics, y2tics, my2tics

gnuplot> set xtics nomirror
gnuplot> unset x2tics #above two commands to remove the scale on the x2
gnuplot> set ytics nomirror
gnuplot> unset y2tics #above two commands to remove the scale on the y2

1.5. Insert text in the figure

gnuplot> set label 'sin (x)' at 0.5,0.5 #in the coordinates (0.5,0.5) adding the string 'sin (x)'

When export figures as .ps or .eps file, if add enhanced in set term statement, you can insert the upper and lower standard, the Greek letters and special symbols. Upper and lower insert is same as Latex

1.6. Adding lines and arrows

gnuplot> set arrow from 0.0,0.0 to 0.6,0.8 #from (0.0,0.0) to (0.6,0.8) draw an arrow
gnuplot> set arrow from 0.0,0.0 to 0.6,0.8 lt 3 lw 2 #color of this arrow type is 3, the line width of type 2
gnuplot> set arrow from 0.0,0.0 to 0.6,0.8 nohead lt 3 lw 2 #nohead can remove the head of the arrow, which is the way to add a straight line

Note that in gnuplot, after insert multiple label or arrow, the system will default according to the order of each label or arrow, respectively, starting from 1. If you later want to remove a label or arrow, as long as corresponding with the unset command can be removed. Such as:
gnuplot> unset arrow 2 #to remove the second arrow

1.7. Size and location of the figure

gnuplot> set size 0.5,0.5 #the length and width are half of the default width recommended to use this value, especially export as .ps or .eps
gnuplot> set origin 0.0,0.5 #set the location of the origin. This figure will appear in the upper left corner

1.8. Three-dimensional graph drawing

gnuplot> splot 'file name' u 2:4:5 #in the second and fourth column as x and y coordinates, and the fifth as z coordinates

1.9. Export the figure to file

In gnuplot, the format of the output file is controlled by the terminal. By default, all outputs send to the screen, that is, the terminal model X11. If you want to output to a file, you must set the terminal. To learn terminal type, you can type set
terminal, all supported the terminal mode (or file format) are listed. For me, always using .ps and .eps files format.
So we can run the following two commands before using plot or splot to draw:

gnuplot> set term post eps color solid enh
gnuplot> set output 'a.eps'

The first command is to set the terminal mode, post is the postscript model, which is to output to ps or eps files. The following eps, color, solid and
enh options can be ignored, depending on your needs. eps means output a eps files, default is output a ps file; color means to output color figure, default is black and white; solid means all the output lines in the figure a solid line, default is only the first line are solid, others are different dotted line; use enh (enhanced) option can inserted subscript, Greek letters and special symbols into figure.

The second command is the output file name. Note, however, run these two commands is just define the output file name, in fact, figure still not be drawn to this file yet. Then run the following command:

gnuplot> plot sin (x) wl
Or
gnuplot> replot (if you have ran plot or replot command before)

At this time, the graphics will in the specified file above.
To export to other formats, the same should be set, such as jpg format, running the following command before drawing command:

gnuplot> set term jpeg
gnuplot> set output 'a.jpg'

If you want to go back to the other modes by the output to the screen, then run the following command:

gnuplot> set term X11





Gnuplot Tips (2)

GNUPLOT Tips (2

How to draw the same graph in the same number of figure

gnuplot> set multiplot #is set to multi-graph mode
gnuplot> set origin 0.0,0.5 #set the first figure the location of the origin
gnuplot> set size 0.5,0.5 #set the first figure of the size of the
gnuplot> plot "a1.dat"
gnuplot> set origin 0.5,0.5 #set the second figure the location of the origin
gnuplot> set size 0.5,0.5 #set the size of the second graph
gnuplot> plot "a2.dat"
gnuplot> set origin 0.0,0.0 #set the origin of the third location figure
gnuplot> set size 0.5,0.5 #set the size of the third graph
gnuplot> plot "a3.dat"
gnuplot> set origin 0.5,0.0 #set the fourth position of the origin figure
gnuplot> set size 0.5,0.5 #set the size of the fourth figure
gnuplot> plot "a4.dat"

Of course, if a graph after a quantity of the same set and the previous one, then after a set amount of this can be omitted. For example, on the face of the second, third and fourth the size of the set plans. The previous figure set on a volume will play a role in the latter figure.If you want to cancel the role of the figure in the back, must use the following commands, such as canceling the label, use
gnuplot> unset label

For two-dimensional graphs, how to make both sides of the axis length of the unit length

gnuplot> set size square #the graph is square
gnuplot> set size 0.5,0.5 #the graph is the size you want
gnuplot> set xrange [-a: a]
gnuplot> set yrange [-a: a] #same as the two axes scale range
gnuplot> plot 'a.dat'

How to use the same graph in the left and right sides of the y-axis are drawing

gnuplot> set xtics nomirror #remove the top of the scale axis x2
gnuplot> set ytics nomirror #to remove the right side of the scale axis y2
gnuplot> set x2tics #above the axis to scale automatically generated x2
gnuplot> set y2tics #to the right side of the scale of the axes automatically generated y2
gnuplot> plot sin (x), cos (x) axes x1y2 #cos (x) with x1y2 coordinates, axes x1y2 x1y2 said axis with
gnuplot> plot sin (x), cos (x) axes x2y2 #cos (x) with x2y2 coordinates, axes x2y2 x2y2 said axis with
gnuplot> set x2range [-20:20] #set the range of coordinates x2
gnuplot> replot
gnuplot> set xrange [-5:5] #set the x coordinate of the range
gnuplot> replot
gnuplot> set xlabel 'x'
gnuplot> set x2label 't'
gnuplot> set ylabel 'y'
gnuplot> set y2label 's'
gnuplot> replot
gnuplot> set title 'The figure'
gnuplot> replot
gnuplot> set x2label 't' textcolor lt 3 #textcolor lt 3 or tc lt 3 set the color of the axis name

How to insert Greek letters and special symbols

Generally only in the ps and eps figure, and must specify the enhanced option. In the X11 terminal (ie display) can not be displayed.

gnuplot> set terminal postscript enhanced and Greek letters can, through {/ Symbol a} input. For example,
gnuplot> set label '{/ Symbol a}'

Greek letters and special symbols of various input methods please see the installation package in gnuplot-4.0.0/docs/psdoc directory ps_guide.ps file.
Another See also:
http://t16web.lanl.gov/Kawano/gnuplot/label-e.html # 4.3

Gnuplot how to insert the Angstrom (Egypt) The symbol (A top of a small circle)

Before you insert the script by adding
gnuplot> set encoding iso_8859_1
This command, and then can use the "{\ 305}" added. Abscissa should be labeled as "k (1 /?)":
gnuplot> set xlabel 'k (1 / {\ 305})
If multiplot mode, this command must be placed in
gnuplot> set multiplot
Front.
If the latter have to escape into other characters, but also added after the character in the insert the following command:
set encoding default
Installation package gnuplot-4.0.0/docs/psdoc/ps_guide.ps file table 'E' on behalf of all the symbols in that column are entered using this method.

Gnuplot drawing contour figures

gnuplot> splot 'file name. dat' u 1:2:3 wl #do three-dimensional figure
gnuplot> set dgrid3d 100,100 #three-dimensional figure the surface of the grid to set the number of
gnuplot> replot
gnuplot> set contour #draw contour set
gnuplot> set cntrparam levels incremental -0.2,0.01,0.2 #set spacing of contour lines and scope of the data at intervals from -0.2 to 0.2 0.01 to draw a line between
gnuplot> unset surface to remove the above three-dimensional graphics
Drop the mouse end graphics, you can choose the right angle. Or directly setting (0,0) perspective can also:
gnuplot> set view 0,0
gnuplot> replot

Note here, drawing three-dimensional figure data file to be partitioned, that is, transform a value for each x, y within the range of its change in a week, so as a piece, and then take an x value, y and then changes a week, as the next a block of data, and so on. Between the blocks to open with a blank line grid.

How to draw beautiful pm3d figure

gnuplot> set pm3d #set pm3d mode
gnuplot> set isosamples 50,50 #set grid
gnuplot> splot x ** 2 + y ** 2 #three-dimensional graph drawing
gnuplot> splot x ** 2 + y ** 2 w pm3d #drawn pm3d mode, note that comparing changes
gnuplot> set view 0,0 #set the view, (0,0) to the surface of the projector in the end
gnuplot> splot x ** 2 + y ** 2 w pm3d #redrawn, note the changes
gnuplot> unset ztics #figures to remove the z axis
gnuplot> set isosamples 200,200 #thinner to the grid
gnuplot> replot #redrawn, note the changes, mainly a more smooth transition

Using a script file to avoid duplication of input

Sometimes a data file of a good figure, the next may have to use this data file to draw, but one or some settings to make some subtle changes. At this time, the first time can be plotted all the commands written to a file, such as a.plt, the next as long as the appropriate setting to do modifications, with the following command will automatically run the file all the commands and the last received you want the figure:

gnuplot> load 'a.plt'

As an example, suppose the file name a.plt, the contents of which are:

set pm3d
set view 0,0
unset ztics
set isosamples 200,200
splot x ** 2 + y ** 2 w pm3d
set term post color
set output 'a.ps'
replot

So start gnuplot, simply run the following command on it:

gnuplot> load 'a.plt'

If we want only the. Ps or. Eps figure, it can also be directly in linux command prompt, run the following command:

[Abc @ Abc] $ gnuplot a.plt

In the linux command gnuplot mode

In the gnuplot prompt can run linux commands, but must be preceded by the corresponding command! Number. For example, suppose a lot of parameters have been set, but need to modify a data file a.dat after drawing, you can use as follows:

gnuplot>! vi a.dat

In this way, all the linux commands can be run in gnuplot environment.
Alternatively, you can enter in the gnuplot prompt shell, temporary exit gnuplot, into the linux environment, done things to do, run the exit command, and went back to gnuplot environment.

gnuplot> shell
[Abc @ Abc] $ vi af
[Abc @ Abc] $ f77 af
[Abc @ Abc] $ a.out (assuming the data file generated a.dat)
[Abc @ Abc] $ exit

gnuplot> plot 'a.dat' wl

海钓真经(入门卷) (转)

海钓真经(入门卷) (转)

By LIFisher@Mitbbs

长岛号称“The fishing capital of the world”,如果在这里呆了好几年,却只知道
抓螃蟹不知海钓为何物,将来想起来可能会有点遗憾哦。屁屁我在国内也是钓淡水鱼,
海钓是来这里才开始学的,想起当初“自学成柴”的艰难,于是愿意将一点心得拿出来
跟大家分享,帮助有兴趣的同学尽快上贼船。

做贼也得守法。所以首先介绍一下相关法律方面的情况。海钓不需要 license,但是各
个州都有它的 regulation,哪种鱼什么时候可以钓,一天每个人可以 keep 几条,什
么样的尺寸是 keeper,什么样的钓到了必须放回大海,都是有规定的。Regulation 每
年都会由 DEC 根据上一年每种鱼的渔获量进行调整。在一些钓点经常会有警察检查,
被查到非法行为,轻则罚款(象一条不合尺寸的 striped bass,可以罚$1000),重则
有牢狱之灾,所以请各位谨记。Regulation 可以到这个网址查看
www.dec.state.ny.us/website/dfwmr/marine/swfl aws.htm

我们附近可以钓的鱼种主要有:
1.Flounder。中文就是比目鱼,但是是冬天的比目鱼。现在正是钓 flounder 的时候。
2.Fluke。也是比目鱼,是夏天的比目鱼。每年从 5 月开始会比较多,能一直钓到 11
月。
3.Striped Bass。海鲈鱼。我最喜欢钓的鱼种,去年钓到的最大只是 22 磅,长岛
local 的高手们都是钓它。但难度比较高,去年一年我只钓了 11 只 keeper。
4.Blue fish。海青鱼。去年我亲眼见到的最大只是小谢钓到的。凶猛有力,牙齿锋利
无比,记得如果不幸拉到一只,一定要先用石头将之砸个半死(最好全死,怕人骂我太
凶残所以不好意思直接说)再去下钩,否则小心手指不见一截(决非恐吓)。 Baby
bluefish 有专门的名字叫 snapper。
5.Porgy。鲷(diao)鱼。这几年周边 porgy 很多,相对比较容易钓,适合作为新手拿
来入门,味道也不错,就是收拾很麻烦。
6.Blackfish。每年 10 月 1 号可以开始钓,就是国内说的石斑。7.Shad。鲱鱼。淡水
的 shad 在国内¥2000/斤,海水的比较便宜,我都是钓来当鱼饵的。
另外还有 cod(鳕鱼),weakfish,sea bass,False Albocore,bonito,tuna,
lobster(去年我的一个朋友还真钓到一只), herring,eel(抓螃蟹的 smithpoint
有很多),有的因为要坐船出外海才能钓到,有的不具备代表性,我就不讨论。

好了好了,不要着急嘛,现在进入技术阶段。想钓到海鱼你首先需要对自然条件有一定
的了解。首先就是潮水。各个钓点潮水时间都不同,可以到这里查:
www.noreast.com/tidesnew/selectlocation.cfm?r egion_ID=33&...

2。理论上每天应该有高潮和低潮各两次(会有某些天只有一次,其实潮水时间自己也
可以推算)。岸边海钓最佳时间是高潮前两个小时到高潮后三个小时,这也根据鱼种,
钓点,时间会有所区别。有的地方有的时候钓退潮(outcoming tide)会比较好,有的
则是涨潮(incomg tide)比较好,这要靠经验,如果没有把握,就只能早点去守在那里
了。然后是月亮的盈亏。这其实还是与潮水有关。每个月最佳的时候是 New Moon(农
历初一),这一天潮水是一个月里最高的,鱼也最活跃,最愿意吃东西,然后就是
Full moon(十五),New Moon 以后的几天往往也很好。每次出去之前,要查查潮水时
间以及潮水高度。尤其是夜钓。接着就是一天之内的区别,清晨和黄昏的时候是鱼最活
跃的时候,也是它们的进食欲望最强的时候。有时候半个小时的差别会是天壤之别。到
7 月进入盛夏,很多鱼基本只能晚上,清晨和黄昏才有机会钓到。

钓点的选择,把它放在最后不是因为它不重要,而是最重要。什么时候选择哪个钓点钓
什么鱼要看经验,也要注意收集其他人的信息。这可以每个星期到 local B&T(Bait &
Tackle shop)去拿免费的 local 钓鱼杂志《Noreast》看,也可以去www.noreast.com
看网络版。咱们附近比较好的钓点有:Rocky Point,那里五月可以开始钓 Striped
bass, bluefish, blackfish, porgy,去年 porgy 尤其多,但是缺点是人太多,进入
7 月岸边基本就没鱼可钓,要去就每天一大早去吧。West Meadow Beach,那里是我六
月钓 Striped Bass 的首选,这里我不详细介绍,等到初学者技术到一定火候,并确实
有兴趣,再跟我联系。Stony Brook Habor。就在那个鸭子湖旁边,往前到船码头那里
。Flounder, Fluke 的大本营。7 月那里经常会看到我。Cold Spring Habor。就是
Cold Spring Habor实验室里面的那个海滩。7 月钓 snapper,9 月 striped bass,这
个钓点是 spear 大虾前年介绍给我的,在此对他表示感谢。Old Field。这是目前我去
得最多的地方。也是附近最佳的钓点。但因为是私人海滩,我也是朋友介绍才能去,所
以没办法广而告之。但是你如果认识那里面的住户(车不能随便停,只能停在人家院子
里),可以尝试一下。Ceder Beach. 也是钓 Fluke 的好地方,但跟 Rocky Point 一
样,进入旺季以后,人比鱼多。以上都是北岸的钓点。南岸因为比较遥远,所以去得不
多,但是 Captree 是很不错的地方,10 月 15 号以后钓 shad,多得难以想象。那里
的螃蟹可以抓到 11 月。

古人说“工欲善其事,必先利其器”。使用“利器”对你的战果将会有显著的影响。鱼
杆和线轮是很有讲究的,这里面更重要的是线轮。但是初学者可以不用着急,立足你目
前拥有的装备好了。然后是鱼钩。不同的鱼需要不同的钩和不同的绑钩方式(Rig),
我有两张详细的图解,介绍了一些常用的 rig 的绑法以及各种结的打法。我会扫描下
来上传到 sparky。初学者也可以到 Sportsauthority 或者 walmart,根据你要钓的鱼
种去买已经绑好的 rig,建议不要买 South Bend 这个牌子的,mustad(不是日货)质
量好很多。鱼线有两种,一种是那种透明的塑料线(Mon ofilament),这种线便宜耐
用,但是弹性比较大,反应比较慢,容易脱钩跑鱼。一种是合成纤维的(Braided),
这种鱼线基本没有弹性,会将你的动作第一时间传到你的鱼钩上,也比较结实。还有一
个好处是同样磅数的 braided 线比monofilament 线轻很多,半径也小很多,这样你就
可以在你的线轮上缠更多的线,鱼饵也会甩得远很多(很重要哦)。但是比较贵,不耐
磨,用一段时间后会磨损,需要更换。初学者可以先去买一卷 monofilament 的线试试
,当你发现自己已经可以拉到鱼,但是鱼经常脱钩,再考虑换用 braided 的线吧。买
鱼线的时候要注意磅数,所谓磅数,就是这种线可以承受多大的拉力却能保证不被拉断
。刚开始钓鱼,不会钓到很大的家伙,买monofilament 线,12 磅左右就足够了,否则
你会发现很难将鱼饵甩远。买 braided, 因为 50 lb test 的线只相当于 12lb
monofilament 的半径和重量,所以不防买磅数比较大的,比较耐用。不过这还是要根
据你的线轮半径决定。一般线轮上都有一些数据表示你的线轮可以缠何种磅数的
monofilament 的线多少码。正常情况下,150 yard 就够了。铅锤的重量要根据你线的
强度和风浪大小决定,我一般用 2-3ounce。大家如果是钓小鱼,用 2 ounce 就可以了
。太小不好,不好甩远。

好,现在谈谈鱼饵。海钓没有用蚯蚓一说(也看到有人用蚯蚓钓到过),钓不同的鱼,
需要去 local 的 bait shop 买不同的鱼饵。有的鱼饵,也可以自己想办法抓。同样的
鱼,不同时间,不同钓点,喜欢的食物也不一样,所以建议每次出去,最好准备两种以
上钓饵。
Flounder:最喜欢吃 mussel, sandworm(海虫)对它们也有很大的杀伤力。Fluke:大
家都用 spearing(一种小小的黄色的小鱼)和 squid 的 combo。Squid 可以去
supermarket 买那种没处理过的,然后自己剪成细长条。活的 kelly+squid 也很好。
Striped Bass: 最喜欢活的 shad,但没卖的,必须自己钓。店里可以买的是 bunker。
一条切成 4-5 块,用盐腌一下,让鱼肉变紧,不容易被小鱼拖跑。记得不要买冷冻的
,最好买 fresh bunker,效果会比较好。Clam, sandworm 在特定的时间特定的地点也
会不错。Porgy:五,六月 rocky point 的 porgy 最喜欢吃 sandworm。也可以用
clam。有新鲜的最好(比较贵),也可以买那种成包的冰冻的,然后自己用多多的盐腌
着,直到脱水,clam 肉变得比较结实,这样不容易被小鱼拖走。Bluefish:饮食习惯
跟 striped bass 一样。Blackfish:green crab。不是我们抓来吃的那种 blue crab
。可以买到,也可以到 west meadow 啊什么的海边乱石堆里翻那种指甲盖大的小螃蟹
。Shad:不吃真饵。去买钓 herring 的 rig,彩色的塑料小管,加上银色的小亮片。
Snapper:只能用那种银色的小亮片钓,那种小亮片在水里拉动是就象银色的小鱼。其
实几乎有的鱼都可以用假饵钓,这放在中级里面讲吧。

CMake在Linux上的使用方法

本文介绍了一个跨平台的自动化构建系统 CMake  linux 上的使用方法。 CMake 是一个比
automake 更加容易使用的工具,能够使程序员从复杂的编译连接过程中解脱出来。文中通过一些例子介
绍使用 CMake 处理多源文件目录的方法、
查找并使用其他开发包的方法以及生成 debug 版和 release
版程序的方法。
CMake 简介
CMake 是一个跨平台的自动化建构系统,它使用一个名为 CMakeLists.txt 的文件来描述构建过程,可以
产生标准的构建文件, Unix  Makefile  Windows Visual C++  projects/workspaces 。文
 CMakeLists.txt 需要手工编写,也可以通过编写脚本进行半自动的生成。CMake 提供了比
autoconfig 更简洁的语法。在 linux 平台下使用 CMake 生成 Makefile 并编译的流程如下:
1. 编写 CmakeLists.txt
2. 执行命令 “cmake PATH” 或者 “ccmake PATH” 生成 Makefile ( PATH  CMakeLists.txt 所在
的目录 )
3.
使用 make 命令进行编译。
第一个工程
现假设我们的项目中只有一个源文件 main.cpp
清单 1 源文件 main.cpp
1 #include<iostream>
2
3 int main()
4 {
5 std::cout<<"Hello word!"<<std::endl;
6 return 0;
7 }
为了构建该项目,我们需要编写文件 CMakeLists.txt 并将其与 main.cpp 放在 同一个目录下:
清单 2 CMakeLists.txt
1 PROJECT(main)
2 CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
3 AUX_SOURCE_DIRECTORY(. DIR_SRCS)
4 ADD_EXECUTABLE(main ${DIR_SRCS})
CMakeLists.txt 的语法比较简单,由命令、注释和空格组成,其中命令是不区分大小写的,符号"#"后面的
内容被认为是注释。命令由命令名称、小括号和参数组成,参数之间使用空格进行间隔。例如对于清单 2 
CMakeLists.txt 文件:第一行是一条命令,名称是 PROJECT ,参数是 main ,该命令表示项目的名称是
main 。第二行的命令限定了 CMake 的版本。第三行使用命令 AUX_SOURCE_DIRECTORY 将当前
目录中的源文件名称赋值给变量 DIR_SRCS  CMake 手册中对命令 AUX_SOURCE_DIRECTORY
的描述如下:
aux_source_directory(<dir> <variable>)
该命令会把参数 <dir> 中所有的源文件名称赋值给参数 <variable>  第四行使用命令
ADD_EXECUTABLE 指示变量 DIR_SRCS 中的源文件需要编译 成一个名称为 main 的可执行文件。
完成了文件 CMakeLists.txt 的编写后需要使用 cmake  ccmake 命令生成 Makefile  ccmake
与命令 cmake 的不同之处在于 ccmake 提供了一个图形化的操作界面。cmake 命令的执行方式如下:
cmake [options] <path-to-source>
这里我们进入了 main.cpp 所在的目录后执行 “cmake .” 后就可以得到 Makefile 并使用 make 
行编译,如下图所示。
 1. camke 的运行结果
处理多源文件目录的方法
CMake 处理源代码分布在不同目录中的情况也十分简单。现假设我们的源代码分布情况如下:
 2. 源代码分布情况
其中 src 目录下的文件要编译成一个链接库。
第一步,项目主目录中的 CMakeLists.txt
在目录 step2 中创建文件 CMakeLists.txt 。文件内容如下:
清单 3 目录 step2 中的 CMakeLists.txt
1 PROJECT(main)
2 CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
3 ADD_SUBDIRECTORY( src )
4 AUX_SOURCE_DIRECTORY(. DIR_SRCS)
5 ADD_EXECUTABLE(main ${DIR_SRCS}
)
6 TARGET_LINK_LIBRARIES( main Test )
相对于清单 2,该文件添加了下面的内容第三行,使用命令 ADD_SUBDIRECTORY 指明本项目包含
一个子目录 src 。第六行,使用命令 TARGET_LINK_LIBRARIES 指明可执行文件 main 需要连接一
个名为 Test 的链接库 
第二步,子目录中的 CmakeLists.txt
在子目录 src 中创建 CmakeLists.txt。文件内容如下:
清单 4. 目录 src 中的 CmakeLists.txt
1 AUX_SOURCE_DIRECTORY(. DIR_TEST1_SRCS)
2 ADD_LIBRARY ( Test ${DIR_TEST1_SRCS})
在该文件中使用命令 ADD_LIBRARY  src 目录中的源文件编译为共享库。
第三步,执行 cmake
至此我们完成了项目中所有 CMakeLists.txt 文件的编写,进入目录 step2 中依次执行命令 “cmake .”
 “make” 得到结果如下:
 3. 处理多源文件目录时 cmake 的执行结果
在执行 cmake 的过程中,首先解析目录 step2 中的 CMakeLists.txt ,当程序执行命令
ADD_SUBDIRECTORY( src ) 时进入目录 src 对其中的 CMakeLists.txt 进行解析。
在工程中查找并使用其他程序库的方法
在开发软件的时候我们会用到一些函数库,这些函数库在不同的系统中安装的位置可能不同,编译的时候需
要首先找到这些软件包的头文件以及链接库所在的目录以便生成编译选项。例如一个需要使用博克利数据
库项目,需要头文件 db_cxx.h 和链接库 libdb_cxx.so ,现在该项目中有一个源代码文件 main.cpp ,
放在项目的根目录中。
第一步,程序库说明文件
在项目的根目录中创建目录 cmake/modules/ , cmake/modules/ 下创建文件
Findlibdb_cxx.cmake ,内容如下:
清单 5. 文件 Findlibdb_cxx.cmake
01 MESSAGE(STATUS "Using bundled Findlibdb.cmake...")
02
03 FIND_PATH(
04 LIBDB_CXX_INCLUDE_DIR
05 db_cxx.h
06 /usr/include/
07 /usr/local/include/
08 )
09
10 FIND_LIBRARY(
11 LIBDB_CXX_LIBRARIES NAMES
12 PATHS /usr/lib/ /usr/local/lib/
13 )
db_cxx
文件 Findlibdb_cxx.cmake 的命名要符合规范: FindlibNAME.cmake ,其中 NAME 是函数库的名称。
Findlibdb_cxx.cmake 的语法与 CMakeLists.txt 相同。这里使用了三个命令: MESSAGE ,
FIND_PATH  FIND_LIBRARY 
• 命令 MESSAGE 会将参数的内容输出到终端。
• 命令 FIND_PATH 指明头文件查找的路径,原型如下:
find_path(<VAR> name1 [path1 path2 ...]) 该命令在参数 path* 指示的目录中查找文件 name1
并将查找到的路径保存在变量 VAR 中。清单 5  3-8 行的意思是在 /usr/include/ 
/usr/local/include/ 中查找文件 db_cxx.h ,并将 db_cxx.h 所在的路径保存在
LIBDB_CXX_INCLUDE_DIR 中。
命令 FIND_LIBRARY  FIND_PATH 类似,用于查找链接库并将结果保存在变量中。清单 5  10-13 
的意思是在目录 /usr/lib/  /usr/local/lib/ 中寻找名称为 db_cxx 的链接库,并将结果保存在
LIBDB_CXX_LIBRARIES 
第二步项目的根目录中的 CmakeList.txt
在项目的根目录中创建 CmakeList.txt :
清单 6. 可以查找链接库的 CMakeList.txt
01 PROJECT(main)
02 CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
03 SET(CMAKE_SOURCE_DIR .)
04 SET(CMAKE_MODULE_PATH ${CMAKE_ROOT}/Modules ${CMAKE_SOURCE_DIR}/cmake/modules)
05 AUX_SOURCE_DIRECTORY(. DIR_SRCS)
06 ADD_EXECUTABLE(main ${DIR_SRCS})
07
08 FIND_PACKAGE( libdb_cxx REQUIRED)
09 MARK_AS_ADVANCED(
10 LIBDB_CXX_INCLUDE_DIR
11 LIBDB_CXX_LIBRARIES
12 )
13 IF (LIBDB_CXX_INCLUDE_DIR AND LIBDB_CXX_LIBRARIES)
14 MESSAGE(STATUS "Found libdb libraries")
15
INCLUDE_DIRECTORIES(${LIBDB_CXX_INCLUDE_DIR})
16 MESSAGE( ${LIBDB_CXX_LIBRARIES} )
17 TARGET_LINK_LIBRARIES(main ${LIBDB_CXX_LIBRARIES}
18 )
19 ENDIF (LIBDB_CXX_INCLUDE_DIR AND LIBDB_CXX_LIBRARIES)
在该文件中第 4 行表示到目录 ./cmake/modules 中查找 Findlibdb_cxx.cmake ,8-19 行表示查找
链接库和头文件的过程。第 8 行使用命令 FIND_PACKAGE 进行查找,这条命令执行后 CMake 会到变
 CMAKE_MODULE_PATH 指示的目录中查找文件 Findlibdb_cxx.cmake 并执行。第 13-19 行是
条件判断语句,表示如果 LIBDB_CXX_INCLUDE_DIR  LIBDB_CXX_LIBRARIES 都已经被赋值,
则设置编译时到 LIBDB_CXX_INCLUDE_DIR 寻找头文件并且设置可执行文件 main 需要与链接库
LIBDB_CXX_LIBRARIES 进行连接。
第三步,执行 cmake
完成 Findlibdb_cxx.cmake  CMakeList.txt 的编写后在项目的根目录依次执行 “cmake . ” 
“make ” 可以进行编译,结果如下图所示:
 4. 使用其他程序库时 cmake 的执行结果
使用 cmake 生成 debug 版和 release 版的程序
 Visual Studio 中我们可以生成 debug 版和 release 版的程序,使用 CMake 我们也可以达到上述
效果。
debug 版的项目生成的可执行文件需要有调试信息并且不需要进行优化, release 版的不需要调
试信息但需要优化。这些特性在 gcc/g++ 中是通过编译时的参数来决定的,如果将优化程度调到最高需
要设置参数-O3,最低是 -O0 即不做优化;添加调试信息的参数是 -g -ggdb ,如果不添加这个参数,调试
信息就不会被包含在生成的二进制文件中。
CMake 中有一个变量 CMAKE_BUILD_TYPE ,可以的取值是 Debug Release RelWithDebInfo 
MinSizeRel。当这个变量值为 Debug 的时候,CMake 会使用变量 CMAKE_CXX_FLAGS_DEBUG 
CMAKE_C_FLAGS_DEBUG 中的字符串作为编译选项生成 Makefile ,当这个变量值为 Release 的时
,工程会使用变量 CMAKE_CXX_FLAGS_RELEASE  CMAKE_C_FLAGS_RELEASE 选项生成
Makefile
现假设项目中只有一个文件 main.cpp ,下面是一个可以选择生成 debug 版和 release 版的程序的
CMakeList.txt :
清单 7
1 PROJECT(main)
2 CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
3 SET(CMAKE_SOURCE_DIR .)
4
5 SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
6 SET(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
7
8 AUX_SOURCE_DIRECTORY(. DIR_SRCS)
9 ADD_EXECUTABLE(main ${DIR_SRCS})
 5  6 行设置了两个变量 CMAKE_CXX_FLAGS_DEBUG  CMAKE_CXX_FLAGS_RELEASE,
这两个变量是分别用于 debug  release 的编译选项。编辑 CMakeList.txt 后需要执行 ccmake 
令生成 Makefile 。在进入项目的根目录,输入 "ccmake ." 进入一个图形化界面,如下图所示:
 5. ccmake 的界面
按照界面中的提示进行操作, "c" 进行 configure ,这时界面中显示出了配置变量
CMAKE_BUILD_TYPE 的条目。如下图所示:
 6. 执行了 configure 以后 ccmake 的界面
下面我们首先生成 Debug 版的 Makefile :
将变量 CMAKE_BUILD_TYPE 设置为 Debug , "c" 
 configure , "g" 生成 Makefile 并退出。这时执行命令 find * | xargs grep "O0" 后结果如下:
清单 8 find * | xargs grep "O0"的执行结果
CMakeFiles/main.dir/flags.make:CXX_FLAGS = -O0 -Wall -g -ggdb
CMakeFiles/main.dir/link.txt:/usr/bin/c++ -O0 -Wall -g -ggdb
CMakeFiles/main.dir/main.cpp.o -o main -rdynamic
CMakeLists.txt:SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
这个结果说明生成的 Makefile 中使用了变量 CMAKE_CXX_FLAGS_DEBUG 作为编译时的参数。
下面我们将生成 Release 版的 Makefile :再次执行命令 "ccmake ." 将变量 CMAKE_BUILD_TYPE
设置为 Release ,生成 Makefile 并退出。执行命令 find * | xargs grep "O0" 后结果如下:
清单 9 find * | xargs grep "O0"的执行结果
CMakeLists.txt:SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
而执行命令 find * | xargs grep "O3" 后结果如下:
清单 10. find * | xargs grep "O3"的执行结果
CMakeCache.txt:CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG
CMakeCache.txt:CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG
CMakeFiles/main.dir/flags.make:CXX_FLAGS = -O3 -Wall
CMakeFiles/main.dir/link.txt:/usr/bin/c++ -O3 -Wall
CMakeFiles/main.dir/main.cpp.o -o main -rdynamic
CMakeLists.txt:SET(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
这两个结果说明生成的 Makefile 中使用了变量 CMAKE_CXX_FLAGS_RELEASE 作为编译时的参数。
参考资料
• 要了解 CMake, 请参考其官方网站:http://www.cmake.org/
• 维基百科中对 CMake 也有非常详细的说明,具体请参考:
http://zh.wikipedia.org/wiki/CMake
 developerWorks Linux 专区 寻找为 Linux 开发人员(包括 Linux 新手入门)准备的更


多参考资料,查阅我们 最受欢迎的文章和教程。