1

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)?

5
  • Sorry I'm on my phone and will expand later on. I very answered this question many times (yes this is a duplicate): we don't need to change makeprg or manually invoke g++ to compile C++ programs from vim. Set $CXXFLAGS and them :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. Commented Jul 25, 2020 at 23:31
  • The help page in question: github.com/LucHermitte/vim-build-tools-wrapper/blob/master/doc/… Commented Jul 25, 2020 at 23:37
  • Thanks @LucHermitte. Commented Jul 26, 2020 at 3:14
  • Highly related: vi.stackexchange.com/q/24561/10604 Commented Jul 26, 2020 at 13:33
  • And again: vi.stackexchange.com/q/15520/10604 Commented Jul 26, 2020 at 13:34

1 Answer 1

1

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

https://github.com/LucHermitte/vim-build-tools-wrapper/blob/master/doc/make_run.md#mono-file-projects

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.