From this post here:


One of the answer is:

autocmd filetype cpp nnoremap <F4> :!g++ % -ggdb -o %:r <CR>
autocmd filetype cpp nnoremap<F5> :!g++ % -ggdb -o %:r && ./%:r <CR>

This works. But I would like to have 2 separate function: one for compile only and the other for run only, instead of compiling and run at the same time. So I changed it to this:

autocmd filetype cpp nnoremap <F4> :!g++ % -ggdb -o %:r <CR>
autocmd filetype cpp nnoremap<F5> : ./%:r <CR>

The first command works, it compiles the cpp file whenever I press F4. The second does not work. The reason, I think is because I am referencing :r, which can only be found from the first command. So, vim does not know what :r is.

Work around

Of course, the fastest way to fix would be to do:

autocmd filetype cpp nnoremap <F4> :!g++ % -ggdb <CR>
autocmd filetype cpp nnoremap<F5> : ./a.out <CR>

On Linux, without specifying the -o flag, g++ will compile into an a.out file, and then I would just run ./a.out. This means that every single cpp file would get compiled to a.out

However, I would like to retain the file name as part of the executable. For example, test.cpp would compile to test...etc.

Is there a way to do this?

TL,DR: With the answer from the links given, how can I compile and retain the file name with 1 shortcut, and then on a separate shortcut, run that executable (with the file name retained)?


1 Answer 1


Following instruction here and install appropriate package and set appropriate flags:


We can just do :make %< and !./ %< to build and compile cpp file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.