根据 INCLUDE 环境变量设置 Vim 的 path 选项

刚才想在 Windows 下简单测试一下程序的行为,当然就没有起 IDE,而是直接上 Vim。小问题来了,根据默认的 path 选项的设置,Vim 是找不到头文件的(使用 gf 或 Ctrl-W_F)。那我们如何能够快速配置 Vim,让它能够找到需要的头文件?

如果你用的是 MinGW 系列的 C/C++ 编译器,这个配置相对来说简单,可以考虑直接硬配置到 _vimrc 里,如:

set path=.,
      \c:/mingw64/include/c++/11.3.0,
      \c:/mingw64/include/c++/11.3.0/x86_64-w64-mingw32,
      \c:/mingw64/include/c++/11.3.0/backward,
      \c:/mingw64/lib/gcc/x86_64-w64-mingw32/11.3.0/include,
      \c:/mingw64/include,
      \c:/mingw64/lib/gcc/x86_64-w64-mingw32/11.3.0/include-fixed,
      \c:/mingw64/x86_64-w64-mingw32/include,
      \,

如果你使用的是 MSVC,那实际上命令行编译器会使用环境变量 INCLUDE(Developer Command Prompt 会自动设置),我们最灵活的方式也是直接把 INCLUDE 变量的内容转成 Vim 的选项。用 Vim 脚本很容易做到,但我们需要注意以下细节:

  • "\" 字符最好统一转成 "/",方便处理。
  • 空格字符 " " 在 Vim 选项里有特殊含义,应当转成 "\ "

下面的脚本可以完成任务(DeepSeek-R1 提供了初版,我修正了问题,并进行了改进):

" Function to convert the INCLUDE environment variable into a form
" suitable for the 'path' option
function! ConvertIncludePath()
  let result = ''
  if exists("$INCLUDE")
    " Split paths by semicolon and clean them
    let include_entries = split($INCLUDE, ';')
    let cleaned_entries = []
    for entry in include_entries
      " Replace backslashes and fix double slashes
      let cleaned = substitute(entry, '\\\+', '/', 'g')
      " Prefix spaces with a backslash
      let cleaned = substitute(cleaned, ' ', '\\ ', 'g')
      call add(cleaned_entries, cleaned)
    endfor
    let result = ',' . join(cleaned_entries, ',')
  endif
  return result
endfunction
                                                                   
" Set Vim's path to match the INCLUDE environment variable
let &path = '.' . ConvertIncludePath() . ',,'

如果想要同时支持 MSVC 和 MinGW,那函数不用动,后面这样写:

" Set Vim's path to match the INCLUDE environment variable
let &path = '.' . ConvertIncludePath()
                                                                   
" Add MinGW64 include paths and current directory
set path+=
      \c:/mingw64/include/c++/11.3.0,
      \c:/mingw64/include/c++/11.3.0/x86_64-w64-mingw32,
      \c:/mingw64/include/c++/11.3.0/backward,
      \c:/mingw64/lib/gcc/x86_64-w64-mingw32/11.3.0/include,
      \c:/mingw64/include,
      \c:/mingw64/lib/gcc/x86_64-w64-mingw32/11.3.0/include-fixed,
      \c:/mingw64/x86_64-w64-mingw32/include,
      \,

不管对别人有没有用,我自己先留个笔记吧。😉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值