0 开发环境
Ubuntu14.04
Vim7.4
1 安装Vim & cscope
sudo apt-get install vim-gnome
sudo apt-get install cscope
关于Cscope介绍,见参考资料[1]。
2 安装cscope.vim插件
可以利用Vundle(参见《Ubuntu14.04(64bit)安装YouCompleteMe》的1.5小节)来安装此插件(与上面安装的cscope是不同的,这里安装的是插件,上面安装的是一个独立的工具)。
3 配置&使用
3.1 生成cscope.out库文件
(1) 只到虑当前目录
和使用ctags生成tags类似,通过下述命令可以生成cscope.out[2]:
在当前目录中生成cscope.out:
cscope -Rb
(2) 添加额外的目录
指定源码绝对路径,查找时不受当前工作路径的限制:
cscope -Rb -s absoluteDir
例如在进行Linux驱动开发的时候,将absoluteDir取为Linux源码所在的目录,然后在驱动项目目录执行上述命令(不是进入Linux源码中哦,而是自己在Linux源码之外所创建的目录)。此时,在进行驱动开发的时候,就可以利用cscope的查找功能了, 而不必将当前目录切换到Linux源码目录中。
(3)添加路径前缀
通过第上述步骤(2)虽然可以达到搜索不受工作路径的影响,但是会有一个副作用:同一个文件会有两个重复的路径,一个相对路径,一个绝对路径。因此,在查找的过程中,会出现重复的结果。
为了避免上述副作用,最好是使用下述命令代替上述第(2)步的命令,同样可以达同样的目的,并避免了副作用:
cscope -Rbqkv -P pwd
-P,表示为搜索路径添加前缀, pwd是获取当前工作路径的命令。
3.2 添加目录/库文件
(1)手动方式
打开vim之后,可以通过下述命名添加目录
:cs add directory
或者
:cscope add directory
(2)自动方式一
也可以将下面语句添加到vim的配置文件.vimrc中
if filereadable("cscope.out")
cs add cscope.out
elseif $CSCOPE_DB != ""
cs add $CSCOPE_DB
endif
这样子就会在打开vim的时候自动加载当前目录下车cscope.out文件。
(3)自动方式二
autoload_cscope.vim插件更方便,它会先在当前目录查找cscope.out,有则加载,否则进入其父目录查找,直到找到可用的cscope.out为止。
3.3 find命令
Cscope的功能通过它的子命令find来实现。
:cs find c|d|e|g|f|i|s|t name
其中各个参数意义如下[5]:
s -- symbol:find all references to the token under cursor
g -- global:find global definition(s) of the token under cursor
c -- calls:find all calls to the function name under cursor
t -- text:find all instances of the text under cursor
e -- egrep:egrep search for the word under cursor
f -- file:open the filename under cursor
i -- includes:find files that include the file name under cursor
d -- called:find functions that function under cursor calls
3.4 快捷键映射
为了便于查找,根据参考资料[4][5]的提示,可以在.vimrc中设置上述各命令的快捷映射:
nmap :cs find s =expand("")
nmap :cs find g =expand("")
nmap :cs find c =expand("")
nmap :cs find t =expand("")
nmap :cs find e =expand("")
nmap :cs find f =expand("")
nmap :cs find i ^=expand("")$
nmap :cs find d =expand("")
使用时,将光标停留在要查找的对象上,按下Ctrl + g,将会查找该对象的定义(这里使用Ctrl是为了避免和vim的原有快捷方式冲突);其它的快捷方式使用如Shift+ s/c/t/e/f/i/d。
4 java支持
默认情况下,cscope只会分析c/c++代码,忽略java代码,在进行Android开发时,这很不方便。为了添加对java的支持,可以这么做。
参考资料[8]支出,cscope会在当前目录中的cscope.files文件中查找要分析的文件列表(如果没有cscope.files,cscope就以当前目录中的c/c++文件)。因此,可以将需要分析的源文件都写进cscope.files目录中,然后再生成数据库,这样子就可以支持java了。
find . -type f -name *.java > cscope.files
find . -type f -name *.c >> cscope.files
find . -type f -name *.c++ >> cscope.files
find . -type f -name *.h >> cscope.files
cscope -Rbqkv -P pwd
参考资料
[1]cscope_百度百科
[2]vim如何跳转到函数定义处及找到在何处被调用-cscope使用
[3]Cscope的使用(领略Vim + Cscope的强大魅力)
[4]Vim + Cscope打造Linux下的Source Insight
[5]CSCOPE 安装和使用方法总结
[6]cscope可以简析JAVA文件
[7]cscope 支持 java c++
[8]cscope中这样生成cscope.files