From this post here:
https://stackoverflow.com/questions/540721/compile-directly-from-vim
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)?
:make %<
navigate errors (:h quickffix) and execute with:!./%<
. Recently I ve given more details on reddit, and I also expand on the subject in an help page of my buildtoolswrapper plugin.