set keybinding for compiling c++ program in neovim

Firstly, open your Neovim configuration file:

nvim ~/.config/nvim/init.vim

Then, add the following lines to set a keybinding for compiling C++ programs in Neovim:

" Compile C++ program with g++
autocmd FileType cpp nnoremap <F5> :w<CR>:!g++ % -o %< && ./%<CR>

Explanation of the steps:

  1. autocmd FileType cpp - This command sets up an auto-command that triggers when editing a file with the .cpp extension.
  2. nnoremap <F5> - This maps the key <F5> in normal mode to the subsequent commands.
  3. :w<CR> - This saves the current file.
  4. :!g++ % -o %< - This runs the g++ compiler on the current file (%) and specifies the output executable name as %<, which removes the file extension.
  5. && ./%<CR> - If the compilation succeeds (&&), it executes the compiled program.

Finally, save the changes to the Neovim configuration file and restart Neovim for the changes to take effect.