Compiling and Running a C++ Program with Vim

Cannot compile and run a c program using vim

This is a solution typically for windows under MINGw. GCC is the name of the compiler application. So the idea is to call gcc and provide it with the name of the file which is to be compiled. The name means the complete path to the file with the file name and extension.

Then we can either execute the a.out file or rename the executable file with the name of the actual file without the extension. So gcc has -o for renaming files. The last job is to call the executable.

:!gcc % :! gcc % -o %< :! %< This is the total command. One can map all these commands on to one key or separate them as per their needs. :! opens the command line in VIM. % is the name of the file with the exact file path. In %< the < just curtails the file extension.

This is what I have put in my vimrc file.

map <F2> :! gcc % <CR>

map <F3> :! gcc % -o %< <CR>

map <F4> :! %< <CR>

Vim - compiling a C program and displaying the output in a tab

:make && ./hello

Did you try this ?

Alternatively, try below

:make && ./hello | copen

vim :make to compile and run C code if it's a success

There is a way with pure vim to do it, but it is a bit of annoying.

Using QuickFixCmdPost(Autocmd Event) to check if there is building error after ':make' ran.
And if there are no errors, run the newly compiled program.

autocmd QuickfixCmdPost make call AfterMakeC()
function! AfterMakeC()
" No any error after make
if len(getqflist()) == 0
!./a.out
endif
" :~)
endfunction

You may want to put the script under namespace in compiler plugin

How can I write a shortcut to compile and run a program in a separate terminal window in Vim?

You actually have a few options, so use whatever suits your needs the most.

You can use vim's built in terminal :terminal (or :term; see :help :terminal), which is probably the easier way:

:term g++-11 %:p && ./a.out<CR>

Or you can use :compiler with :make (see :help :compile and :help 'makeprg'):

:compiler gcc
:let $CXXFLAGS='-std=c++20 -Wall -Werror'
:make

How do I compile C programs using Vim's 'make' command with Visual Studio's compiler on Windows 7?

I believe the problem with your makeprg statement is mostly due to the spaces in the path. Cmd.exe requires double quotes around the spaces. First, use escaped double quotes around the path (\"). Next escape all back slashes (\). Finally, escape all spaces (\ ).

set makrprg=\"c:\\Program\ Files\ (x86)\\Microsoft\ Visual\ Studio\ 10.0\\VC\\bin\\cl.exe\"

Alternatively, you could setup your PATH appropriately and just set makeprg to cl.exe directly.



Related Topics



Leave a reply



Submit