Skip to content

Better way for C and Cpp development in Vim 8

Linwei edited this page Apr 27, 2018 · 29 revisions

I mainly use vim to write C/C++ codes, and the plugin AsyncRun is originated for C/C++ development. Here is a quick glance for speeding up your work flow:

Quick setup

Plug 'skywind3000/asyncrun.vim'

" automatically open quickfix window when AsyncRun command is executed
" set the quickfix window 6 lines height.
let g:asyncrun_open = 6

" ring the bell to notify you job finished
let g:asyncrun_bell = 1

" F10 to toggle quickfix window
nnoremap <F10> :call asyncrun#quickfix_toggle(6)<cr>

When you input :AsyncRun echo hello in the command line:

You will see the realtime command output in the open quickfix window.

Compile and run a single C/C++ file

Let's take a look at single file compilation, just like the build system in sublime, we can setup F9 for this:

nnoremap <silent> <F9> :AsyncRun gcc -Wall -O2 "$(VIM_FILEPATH)" -o "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>

The macros in $(..) form will be expanded as the real file name or directory, and then we will have F5 for run:

nnoremap <silent> <F5> :AsyncRun -raw -cwd=$(VIM_FILEDIR) "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>

The double quotation mark is used to handle path names containing spaces. The option -cwd=$(VIM_FILEDIR) means running the file in the file's directory. The absolute path name $(VIM_FILEDIR)/$(VIM_FILENOEXT) is used because linux needs a ./ prefix to running executables in current directory, but windows doesn't . Using the absolute path name of the binary file can handle this crossing platform issue.

Another option -raw means the output will not be matched by vim's errorformat, and will be displayed in quickfix as what it is. Now you can compile your file with F9, check the compilation errors in quickfix window and press F5 to run the binary.

Clone this wiki locally