Clang是一个C/C++/ObjectC语言的编译器前端,采用LLVM作为后端提供了一个性能接近GCC的编译器。不过我们现在的目标是使用Clang帮助进行代码分析和补全。
首先去Clang的官方网站下载一套编译安装,官方网站地址是:http://clang.llvm.org/
接下来需要安装auto-complete,下载一份,http://cx4a.org/software/auto-complete/,解压缩后,安装,只需要load-file install.el然后按照提示复制4行到.emacs文件即完成了安装。
接下来是auto-complete的clang插件,下载地址,https://github.com/brianjcj/auto-complete-clang
解压缩到任何地方,并将该路径add-to-list,例如:
[plain] view plaincopyprint?
(add-to-list 'load-path "~/.mylisp/")
接下来做一些配置,按照给出的模板进行修改即可:
[plain] view plaincopyprint?
(require 'auto-complete-clang)
(setq ac-clang-auto-save t)
(setq ac-auto-start t)
(setq ac-quick-help-delay 0.5)
;; (ac-set-trigger-key "TAB")
;; (define-key ac-mode-map [(control tab)] 'auto-complete)
(define-key ac-mode-map [(control tab)] 'auto-complete)
(defun my-ac-config ()
(setq ac-clang-flags
(mapcar(lambda (item)(concat "-I" item))
(split-string
"
/usr/include/c++/4.4
/usr/include/c++/4.4/i486-linux-gnu
/usr/include/c++/4.4/backward
/usr/local/include
/usr/lib/gcc/i486-linux-gnu/4.4.5/include
/usr/lib/gcc/i486-linux-gnu/4.4.5/include-fixed
/usr/include/i486-linux-gnu
/usr/include
")))
(setq-default ac-sources '(ac-source-abbrev ac-source-dictionary ac-source-words-in-same-mode-buffers))
(add-hook 'emacs-lisp-mode-hook 'ac-emacs-lisp-mode-setup)
;; (add-hook 'c-mode-common-hook 'ac-cc-mode-setup)
(add-hook 'ruby-mode-hook 'ac-ruby-mode-setup)
(add-hook 'css-mode-hook 'ac-css-mode-setup)
(add-hook 'auto-complete-mode-hook 'ac-common-setup)
(global-auto-complete-mode t))
(defun my-ac-cc-mode-setup ()
(setq ac-sources (append '(ac-source-clang ac-source-yasnippet) ac-sources)))
(add-hook 'c-mode-common-hook 'my-ac-cc-mode-setup)
;; ac-source-gtags
(my-ac-config)
需要说明的几点是:
ac-clang-flags是头文件的目录,根据系统的不同可能你的头文件目录也会不同,列出系统中所有的头文件目录方法是:
[plain] view plaincopyprint?
$ echo "" | g++ -v -x c++ -E -
你可能会找到类似这样的行:
[plain] view plaincopyprint?
include "..." search starts here:
include <...> search starts here:
/usr/include/c++/4.4
/usr/include/c++/4.4/i486-linux-gnu
/usr/include/c++/4.4/backward
/usr/local/include
/usr/lib/gcc/i486-linux-gnu/4.4.5/include
/usr/lib/gcc/i486-linux-gnu/4.4.5/include-fixed
/usr/include/i486-linux-gnu
/usr/include
End of search list.
中间列出的那些目录就是你需要的,替换上面代码中的目录即可
ac-auto-start参数是ac的提示是否自动启动,如果不自动启动的话,将它设为nil即可,你需要补全的时候自己按快捷键进行补全,快捷键的设置方法是:
[plain] view plaincopyprint?
(define-key ac-mode-map [(control tab)] 'auto-complete)
如果这一项设置为t,ac则会自动在有补全的地方列出可补全的项。
有的机器使用的是旧版本的clang,比如假如你使用某个古代发行版自带的旧版本clang,不支持通过stdio进行交互,则需要自动保存文件才能正确调用clang获取补全提示,设置的方法是:
[plain] view plaincopyprint?
(setq ac-clang-auto-save t)
当然新版本的clang可能就不需要这一项了。