Vim C/C++的一键编译

开始用Vim差不多有两个月的时间, 一开始用Makefile 编译一整个项目无压力, 但是当写到单个文件的时候, 编译就比较麻烦了, 每次都得
:w
:!gcc -o 1.exe 1.c
:!1
非常麻烦...所以我都直接用的Code::Blocks...其实比Vim快多了哈哈...

但是昨晚折腾病发作, 想好好来配置一下, 于是花了一个晚上...改了一个能看得过去的一键编译.
原来的代码出自: http://www.vimer.cn/2009/10/11.html 这个域名好羡慕...
觉得他考虑的东西太多而且不好用, 自己折腾了折腾.
所幸vim的帮助文件非常全面, 改动他并不是难事.
代码及注释如下:

 

  1 "单个文件编译 Linux 下大概有问题

 2 "

 3 "

 4 map <F9> :call Do_OneFileMake()<CR> 

 5 "判断操作系统

 6 if(has("win32") || has("win95") || has("win64") || has("win16"))

 7     let g:iswindows=1

 8 else

 9     let g:iswindows=0

10 endif

11 "函数体

12 function Do_OneFileMake()

13     "关闭之前可能存在的QucikFix窗口

14     execute "cclose"    

15     "判断文件路径和工作目录是否相同(其实我也不知道为什么要判断

16     if expand("%:p:h")!=getcwd()

17         echohl WarningMsg | echo "Fail to make! This file is not in the current dir! " | echohl None

18         return

19     endif

20     "sourcefilename 功能未知, 判断该类型是否被支持

21     let sourcefileename=expand("%:t")

22     if (sourcefileename=="" || (&filetype!="cpp" && &filetype!="c"))

23         echohl WarningMsg | echo "Fail to make! Please select the right file!" | echohl None

24         return

25     endif

26     "编译前先保存

27     exec "w" 

28     "设置make参数,

29     "Linux 和 Windows的情况不同, Linux的执行是./*.out Windows的是 *.exe Linux 下的没有经过测试o

30     "makeprg 是 make的参数, 如果 makeprg=make 就执行真正的make.exe,  寻找目录下的makefile, 如果不是make的话这个参数就相当于makefile 的内容, 但是无论如何错误信息都会被送到QuickFix窗口.(暂时的粗浅理解

31     "makeprg中空格和双引号都需要用反斜杠"\"转义

32     if &filetype=="c"

33         if g:iswindows==1

34            set makeprg=gcc\ -o\ \"%<.exe\"\ \"%\"

35         else

36            set makeprg=gcc\ -o\ \"%<\"\ \"%\"

37         endif

38     elseif &filetype=="cpp"

39         if g:iswindows==1

40             set makeprg=g++\ -o\ \"%<.exe\"\ \"%\"

41         else

42             set makeprg=g++\ -o\ \"%<\"\ \"%\"

43         endif

44     endif

45     "删除旧文件, outfilename是生成程序的完整路径

46     let outfilename=expand("%:r").".exe"

47     if filereadable(outfilename)

48         if(g:iswindows==1)

49             let outdeletedsuccess=delete(outfilename)

50         else

51             let outdeletedsuccess=delete("./".outfilename) "doesn't work

52         endif

53         "如果文件删除不了报错

54         if(outdeletedsuccess!=0)

55             set makeprg=make

56             echohl WarningMsg | echo "Fail to make! I cannot delete the ".outfilename | echohl None

57             return

58         endif

59     endif

60     "静默编译, silent 关键字用于静默执行

61     execute "silent make"

62     set makeprg=make  

63     "编译后如果文件存在,说明编译成功, 执行之

64     if filereadable(outfilename)

65         if(g:iswindows==1)

66             execute "!\"%<.exe\""

67             return 

68         else

69             execute "!\"./%<.out\""

70             return 

71         endif

72     endif

73     "不成功弹出错误信息, 即QuickFix窗口

74     execute "silent copen 6"

75 endfunction

 

 



以上.

你可能感兴趣的:(c/c++)