Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use cppcheck when I execute :wq in Vim editor for c/c++

Tags:

vim

cppcheck

I want to override wq/q/w!/w/q! to user defined command along with its functionality.

Example :

If I use :wq to exit, the command should do static code check of that particular c/c++ file and exit.

Please help me in this case.

Thanks in advance.

like image 754
Ram Avatar asked Jan 26 '26 05:01

Ram


1 Answers

The built in solution to your problem is called an "autocommand" in Vim.

It is a way to invoke a command at a specific time like opening, saving or closing a buffer.

See :help autocmd for the full list

In your case, you should add to your .vimrc the following command

autocmd BufWritePre *.cpp,*.hpp !cppcheck %

  • BufWritePre means 'before writing the buffer' (You can also use BufWrite or BufWritePost)
  • *.cpp,*.hpp means the auto command will only be applied when saving cpp or hpp files. You can add c and h files if you want.
  • % means 'path of the current buffer'
  • cppcheck must be in your path

You are not overriding the defaut behaviour of 'w' but you are using 'hooks' to add custom commands.

like image 124
Xavier T. Avatar answered Jan 28 '26 23:01

Xavier T.