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:
autocmd FileType cpp
- This command sets up an auto-command that triggers when editing a file with the.cpp
extension.nnoremap <F5>
- This maps the key<F5>
in normal mode to the subsequent commands.:w<CR>
- This saves the current file.:!g++ % -o %<
- This runs theg++
compiler on the current file (%
) and specifies the output executable name as%<
, which removes the file extension.&& ./%<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.