Is there a way to compile and run a C program from VIM without typing its filename ?
有没有一种不用输入文件名就能从VIM编译和运行C程序的方法?
10 个解决方案
#1
85
:!gcc -o somename % && ./somename
When using :!
, % will be substituted by the name of the currently opened file.
:!在使用时使用:!, %将被当前打开的文件的名称所替代。
When your project becomes larger, you can also write a makefile and compile the current project with :make
, if there are any errors, vim will jump to them automatically.
当您的项目变得更大时,您还可以编写一个makefile并使用:make编译当前的项目,如果有任何错误,vim将自动跳转到它们。
#2
31
Use the following mapping code in your .vimrc file for compiling and running a c programming file.
在.vimrc文件中使用以下映射代码来编译和运行c编程文件。
map <F8> : !gcc % && ./a.out <CR>
F8 key is for run the mapping. "%" is to take the current file name.
F8键用于运行映射。“%”取当前文件名。
Or, if you want to save the current file before compiling it, use
或者,如果您想在编译之前保存当前文件,请使用
map <F8> :w <CR> :!gcc % && ./a.out <CR>
Or more ideally, if you want to use the file basename not the default 'a.out' as the executable file name, use the following:
或者更理想的是,如果您希望使用文件basename而不是默认的'a '。“out”作为可执行文件名,使用以下内容:
map <F8> :w <CR> :!gcc % -o %< && ./%< <CR>
In the above command, "<" after "%" removes extension and dot (foo.c => foo), so "%<" is the file basename.
在上面的命令中,“<”在“%”之后删除扩展名和点(foo)。c => foo),所以“%<”是文件basename。
You can find this and similar infos in cmdline.txt. Command in vim:help: cmdline.txt
. You can also find specific details about the use of "%" by using :help filename-modifiers
in vim.
您可以在cmdlin .txt中找到类似的信息。在vim命令:帮助:cmdline.txt。您还可以通过使用:help fil珐琅-modifiersin vim找到有关使用“%”的具体细节。
#3
5
since most of the time you would use a Makefile, in addition to the given answers, I also like to see my results in a "cleared" screen:
由于大多数时候您会使用Makefile,除了给定的答案之外,我还希望在“清除”屏幕中看到我的结果:
map <F10> :w<CR> :!clear; make<CR> :!./%<<CR>
地图< F10 >:w < CR >:!清晰;使< CR >:! / % < < CR >
-
:w<CR>
saves the file:w < CR >保存该文件
-
:!clear; make<CR>
clears the screen and runsmake
:!清晰;使
清除屏幕并运行make -
:!./%<<CR>
runs a program (%
) without the extension (<
):!/%< CR>运行一个没有扩展名的程序(%)(<)
#4
5
TL;DR No Makefile is required, tweaking &makeprg
is also completely useless, and yet :make %<
is enough to compile from Vim.
不需要DR Makefile,调整和makeprg也完全没用,但是:make % <足以从vim编译。< p>
Long answer:
长一点的回答:
I duplicate an answer I gave in a closed "duplicate question".
我重复我在封闭的“重复问题”中给出的答案。
Considering we are using vim, and not vi, :make
is the way to go.
考虑到我们使用的是vim,而不是vi,所以:make是正确的方法。
On Linux-like (it also applies to cygwin, but not to mingw on windows -- in mingw case, see the other answers that alter &makeprg
, leave it alone otherwise) systems where gnumake is installed, if you don't have a Makefile in your project, and if your project is made of only one file, just type :make %<
. It will be enough (you can play with $CXXFLAGS
, $CFLAGS
and $LDFLAGS
to tune the compilation options). Then to run the program, type :!./%<
, or with latter versions of vim, run :terminal ./%<
.
类linux(这也适用于cygwin,但不要mingw windows——在mingw情况下,看到其他的答案改变&makeprg,别管它否则)gnumake安装系统,如果你没有一个Makefile在你的项目中,如果你的项目是由只有一个文件,只是类型:让% <。这就足够了(您可以使用$CXXFLAGS、$CFLAGS和$LDFLAGS来调整编译选项)。然后要运行程序,输入:!。/%<,或使用后版本的vim,运行:终端。/%<。
If your project is made of several files, then you'll need a Makefile to take advantage of :make
.
如果您的项目是由几个文件组成的,那么您将需要一个Makefile来利用:make。
If you manage your project with CMake, and if you compile your project in a directory (or several -> debug, release, ...) outside the sources tree, then the integration will require a plugin. AFAIK, I'm the only one to propose such a plugin: BuildToolsWrapper integrates the management of CMake (choice of the build directory, possibility to chose between the debug, or release, or whatever build directory). It has to be coupled with one of the local_vimrc plugin.
如果您使用CMake管理您的项目,并且在源代码树之外的目录(或多个-> debug, release,…)中编译您的项目,那么集成将需要一个插件。AFAIK,我是唯一一个提出这样一个插件的人:BuildToolsWrapper集成了CMake的管理(构建目录的选择,在调试中选择的可能性,或者发布,或者任何构建目录)。它必须与local_vimrc插件之一耦合。
In all cases, calling directly the compiler from within (or outside) Vim with :!g++ -o %< %
or whatever is what we used to do 15 years ago on vi. Vim has a wonderful feature: it can integrate (yes, like in IDE) the compiler. See :h quickfix
. Navigating between errors directly from the editor is much easier than extracting one error line with our eyes, typing back the line number into the editor, going back to the shell to see what exactly was rejected, ... It may be enough in C, but In C++ when we are "trying to call an overload that doesn't exist", we can't work this way (switching back and forth between the editor and the shell).
在所有情况下,直接从Vim内部(或外部)调用编译器:!g++ -o %< %或者我们15年前在vi上做的任何事情。Vim有一个很棒的特性:它可以集成(是的,就像在IDE中一样)编译器。看:h quickfix。直接从编辑器中导航错误要比用我们的眼睛提取一条错误线、将行号输入编辑器、返回shell以查看什么被拒绝要容易得多……在C语言中可能已经足够了,但是在c++语言中,当我们“试图调用一个不存在的重载”时,我们不能以这种方式工作(在编辑器和shell之间来回切换)。
Finally, if you want to compile on a single keystroke those mono-file projects, you can add in your .vimrc:
最后,如果您想要在一个击键上编译那些单文件项目,您可以添加.vimrc:
nnoremap <silent> <f7> :make %<<cr>
If you want to adapt automatically the compilation command depending of the kind of project mono-file pet project, or real world multi-file project, well, more wiring is needed, and this is what BTW does -- it reads various options to know what to do.
如果您想根据项目的单文件pet项目或真实世界的多文件项目自动调整编译命令,那么需要更多的连接,而这正是BTW所做的——它读取各种选项以知道该做什么。
Last note: &makeprg
is best left alone, at least not set to g++/gcc/clang/clang++/gfortran/... Because, every time you change your language, you'll have to change it (unless you use :setlocal
). With the solution I recommend, if I want to use clang++ instead of g++, all I have to do is to set: :let $CXX='clang++'
(or $CC
in C), and then call :make %<
. I can even define :let $CXXFLAGS='-std=c++11'
to compile in C++11 -- the same variable will be used to turn warnings on, to use a sanitizer, etc.
最后注意:&makeprg最好不要使用,至少不要设置为g++/gcc/clang/clang++/gfortran/…因为,每次您更改语言时,都必须更改它(除非您使用:setlocal)。对于我推荐的解决方案,如果我想使用clang+而不是g++,我只需设置:::让$CXX='clang++'(或$CC in C),然后调用:make %<。我甚至可以定义:让$CXXFLAGS='-std=c++11'编译在c++11中——相同的变量将被用来打开警告,使用消毒器等等。
#5
4
Add this line in your vimrc
file
在vimrc文件中添加这一行
nnoremap <silent> <F8> :!clear;gcc % -o % && ./%<CR>
Now you only have to press f8 key to compile and run your c program.
现在,您只需按f8键编译并运行您的c程序。
#6
2
Just thought I would add this to these answers here. As has been mentioned, you can use the :make
command in vim. What has not been mentioned yet, is that :make
can invoke other programs, other than make
.
我只是想把这个加到这些答案中。如前所述,您可以在vim中使用:make命令。还没有提到的是:make可以调用除make之外的其他程序。
:set makeprg=gcc\ %
Will cause :make
to execute gcc
with the %
symbol replaced by the current file name.
将导致:使以当前文件名替换的%符号执行gcc。
You can then get fancy and do
然后你就可以开始幻想了。
:set makeprg=gcc\ %\ &&\ ./a.out
and simply typing :make
will compile and execute your program. You can do this for other languages as well of course.
简单地输入:make将编译并执行您的程序。当然,对于其他语言也可以这样做。
:set makeprg=cabal\ repl
:set makeprg=python\ %
#7
1
After doing some research (including this very page), I made my mind to add this shortcut:
在做了一些研究(包括这一页)之后,我决定添加这个快捷方式:
map <F9> :w<CR> :!gcc % -o %<.x -Wall -Wextra 2>errors.err; cat errors.err<CR>
You can also include -ansi -pedantic-errors
if you will.
如果您愿意,您还可以包含-ansi - pedanmy错误。
The errors.err
file will help you with vi quickfix.
的错误。err文件将帮助您处理vi quickfix。
#8
1
It's 2018 now, vim 8 has released for 2 years and shipped with all the Linux distributions and Mac OS X. But a lot of vim tutorials are still teaching people something ten years ago.
现在已经是2018年了,vim 8已经发布了2年,并随所有Linux发行版和Mac OS x一起发布。
You can compile your C++/Java programs in vim as convenience as Sublime Text or NotePad++ with some dedicated plugins for Vim 8 or NeoVim.
你可以在vim中编译你的c++ /Java程序,因为它可以像卓越的文本或NotePad++那样使用一些专用的vim 8或NeoVim插件。
For example, the AsyncRun plugin will allow you run shell commands in background and read output from quickfix window in realtime. See the screen capture.
例如,AsyncRun插件允许你在后台运行shell命令并实时读取quickfix窗口的输出。看到屏幕截图所示。
Just like compiling programs in IDEs, the compilation errors will be matched by errorformat and be highlighted and become selectable. You can navigate errors in the quickfix window or continue editing while compiling.
就像在ide中编译程序一样,编译错误将与errorformat匹配,并被突出显示并成为可选择的。您可以在quickfix窗口中导航错误,或者在编译时继续编辑。
Quick setup
快速设置
Copy & paste the lines below to your vimrc:
复制并粘贴下面的行到您的vimrc:
Plug 'skywind3000/asyncrun.vim'
" open quickfix window automatically when AsyncRun is executed
" set the quickfix window 6 lines height.
let g:asyncrun_open = 6
" ring the bell to notify you job finished
let g:asyncrun_bell = 1
" F10 to toggle quickfix window
nnoremap <F10> :call asyncrun#quickfix_toggle(6)<cr>
When you input “:AsyncRun echo hello ” in the command line:
当您在命令行输入“:AsyncRun echo hello”时:
看到这里的捕获
You will see the realtime command output in the open quickfix window.
您将在open quickfix窗口中看到实时命令输出。
Compile and run a single file
编译并运行一个文件
Compiling a single file with AsyncRun is much simpler than Sublime Text’s build system. We can setup F9 for this:
用AsyncRun编译一个文件要比编写一个优秀的文本构建系统简单得多。我们可以为此设置F9:
noremap <silent> <F9> :AsyncRun gcc -Wall -O2 "$(VIM_FILEPATH)" -o "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>
The macros in $(..)
form will be expanded as the real file name or directory, and then we will have F5 to run the executable:
$(.. .)表单中的宏将扩展为实际文件名或目录,然后我们将有F5运行可执行文件:
noremap <silent> <F5> :AsyncRun -raw -cwd=$(VIM_FILEDIR) "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>
The double quotation mark is used to handle path names containing spaces. The option -cwd=$(VIM_FILEDIR)
means running the file in the file's directory. The absolute path name $(VIM_FILEDIR)/$(VIM_FILENOEXT)
is used because linux needs a ./
prefix to running executables in current directory, but windows doesn't . Using the absolute path name of the binary file can handle this crossing platform issue.
双引号用于处理包含空格的路径名。选项-cwd=$(VIM_FILEDIR)表示在文件的目录中运行文件。使用绝对路径名$(VIM_FILEDIR)/$(VIM_FILENOEXT)是因为linux需要一个./前缀来运行当前目录中的可执行文件,但windows不需要。使用二进制文件的绝对路径名可以处理这个交叉平台问题。
Another option -raw
means the output will not be matched by vim's errorformat, and will be displayed in quickfix as what it is. Now you can compile your file with F9, check the compilation errors in quickfix window and press F5 to run the binary.
另一个选项-raw意味着输出将不会被vim的errorformat匹配,并将显示在quickfix中。现在可以使用F9编译文件,检查quickfix窗口中的编译错误,并按F5运行二进制文件。
Build C/C++ Projects
构建C / c++项目
No matter what build tool you are using, make or cmake, project building means acting to a group of files. It requires locating the project root directory. AsyncRun uses a simple method called root markers to identify the project root. The Project Root is identified as the nearest ancestor directory of the current file which contains one of these directories or files:
无论您使用什么构建工具、make还是cmake,项目构建都意味着对一组文件进行操作。它需要定位项目根目录。AsyncRun使用一种简单的方法,称为根标记来标识项目根。项目根目录被标识为当前文件中最近的祖先目录,其中包含以下目录或文件:
let g:asyncrun_rootmarks = ['.svn', '.git', '.root', '_darcs']
If none of the parent directories contains these root markers, the directory of the current file is used as the project root. This enables us to use either <root>
or $(VIM_ROOT)
to represent the project root. and F7 can be setup to build the current project:
如果任何父目录都不包含这些根标记,则将当前文件的目录用作项目根。这使我们可以使用
noremap <silent> <F7> :AsyncRun -cwd=<root> make <cr>
What if your current project is not in any git or subversion repository ? How to find out where is my project root ? The solution is very simple, just put an empty .root file in your project root, it will be located easily.
如果当前项目不在任何git或subversion存储库中,该怎么办?如何找到我的项目根目录?解决方案非常简单,只需在项目根中放入一个空的.root文件,就可以轻松地找到它。
Let’s move on, setup F8 to run the current project:
让我们继续,安装F8以运行当前项目:
noremap <silent> <F8> :AsyncRun -cwd=<root> -raw make run <cr>
The project will run in its root directory. Of course, you need define the run rule in your own makefile. then remap F6 to test:
该项目将在其根目录中运行。当然,您需要在自己的makefile中定义运行规则。然后将F6重新映射到测试:
noremap <silent> <F6> :AsyncRun -cwd=<root> -raw make test <cr>
If you are using cmake, F4 can be map to update your Makefile:
如果您正在使用cmake,可以使用F4来更新您的Makefile:
nnoremap <silent> <F4> :AsyncRun -cwd=<root> cmake . <cr>
Due to the implementation of c runtime, if the process is running is a non-tty environment, all the data in stdout will be buffered until process exits. So, there must be a fflush(stdout)
after your printf
statement if you want to see the real-time output. or you can close the stdout buffer at the beginning by
由于c运行时的实现,如果进程运行的是一个非tty的环境,那么stdout中的所有数据将被缓冲,直到进程退出。因此,如果您希望看到实时输出,那么在printf语句之后必须有一个fflush(stdout)。或者您可以在开始时关闭stdout缓冲区
setbuf(stdout, NULL);
At the mean time, if you are writing C++ code, a std::endl can be appended to the end of std::cout. It can force flush the stdout buffer. If you are developing on windows, AsyncRun can open a new cmd window for the child process:
同时,如果您正在编写c++代码,那么std::endl可以附加到std::cout的末尾。它可以强制刷新stdout缓冲区。如果您正在windows上开发,AsyncRun可以为子进程打开一个新的cmd窗口:
nnoremap <silent> <F5> :AsyncRun -cwd=$(VIM_FILEDIR) -mode=4 "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>
nnoremap <silent> <F8> :AsyncRun -cwd=<root> -mode=4 make run <cr>
Using the option -mode=4
on windows will open a new prompt window to run the command, just like running command line programs in Visual Studio. Finally, we have these key mappings below:
在windows上使用选项-mode=4将打开一个新的提示窗口来运行命令,就像在Visual Studio中运行命令行程序一样。最后,我们有以下关键映射:
- F4: update Makefile with cmake.
- F4:用cmake更新Makefile。
- F5: run the single file
- F5:运行单个文件
- F6: run project test
- F6:运行测试项目
- F7: build project
- F7:建设项目
- F8: run project
- F8:运行项目
- F9: compile the single file
- F9:编译单个文件
- F10: toggle quickfix window
- F10:切换quickfix窗口
It is more like build system in NotePad++ and GEdit. If you are using cmake heavily, you can write a simple shell script located in ~/.vim/script/build.sh
to combine F4 and F7 together: it will update Makefile if CMakeList.txt has been changed, then exectute make.
它更像是记事本++和GEdit中的构建系统。如果大量使用cmake,可以编写位于~/.vim/script/build中的简单shell脚本。sh将F4和F7合并在一起:它将更新Makefile if CMakeList。txt已经更改,然后执行。
Advanced usage
高级用法
You can also define shell scripts in your dotfiles repository and execute the script with F3:
您还可以在您的dotfiles存储库中定义shell脚本,并使用F3执行脚本:
nnoremap <F3> :AsyncRun -cwd=<root> sh /path/to/your/dotfiles/script/build_advanced.sh <cr>
The following shell environment variables are defined by AsyncRun:
异步调用定义了以下shell环境变量:
$VIM_FILEPATH - File name of current buffer with full path
$VIM_FILENAME - File name of current buffer without path
$VIM_FILEDIR - Full path of current buffer without the file name
$VIM_FILEEXT - File extension of current buffer
$VIM_FILENOEXT - File name of current buffer without path and extension
$VIM_CWD - Current directory
$VIM_RELDIR - File path relativize to current directory
$VIM_RELNAME - File name relativize to current directory
$VIM_ROOT - Project root directory
$VIM_CWORD - Current word under cursor
$VIM_CFILE - Current filename under cursor
$VIM_GUI - Is running under gui ?
$VIM_VERSION - Value of v:version
$VIM_COLUMNS - How many columns in vim's screen
$VIM_LINES - How many lines in vim's screen
$VIM_SVRNAME - Value of v:servername for +clientserver usage
All the above environment variables can be used in your build_advanced.sh
. Using the external shell script file can do more complex work then a single command.
可以在build_advanced.sh中使用上述所有环境变量。使用外部shell脚本文件可以完成比单个命令更复杂的工作。
Grep symbols
Grep的符号
Sometimes, If you don't have a well setup environment in you remote linux box, grep is the most cheap way to search symbol definition and references among sources. Now we will have F2 to search keyword under cursor:
有时,如果您在远程linux box中没有良好的设置环境,那么grep是在源文件中搜索符号定义和引用的最廉价的方法。现在我们有F2在光标下面搜索关键字:
if has('win32') || has('win64')
noremap <F2> :AsyncRun! -cwd=<root> grep -n -s -R <C-R><C-W> --include='*.h' --include='*.c*' '<root>' <cr>
else
noremap <F2> :AsyncRun! -cwd=<root> findstr /n /s /C:"<C-R><C-W>" "\%CD\%\*.h" "\%CD\%\*.c*" <cr>
endif
The above script will run grep or findstr in your project root directory, and find symbols in only .c
, .cpp
and .h
files. Now we move around the cursor and press F2, the symbol references in current project will be displayed in the quickfix window immediately.
上面的脚本将在项目根目录中运行grep或findstr,并且只在.c、.cpp和.h文件中找到符号。现在我们移动光标并按F2,当前项目中的符号引用将立即显示在quickfix窗口中。
This simple keymap is enough for most time. And you can improve this script to support more file types or other grep tools in your vimrc .
这个简单的关键图在大多数情况下都足够了。您可以改进此脚本,以便在vimrc中支持更多的文件类型或其他grep工具。
That’s the practical way to build/run C/C++ projects in Vim 8 or NeoVim. Just like Sublime Text’s build system and NotePad++’s NppExec.
这是在vim8或NeoVim中构建/运行C/ c++项目的实用方法。就像崇高的文本构建系统和记事本+的NppExec。
No more outdated vim tutorials again, try something new.
不再有过时的vim教程,尝试一些新的东西。
#9
0
Add these three lines to your .vimrc
file
将这三行添加到.vimrc文件中
au FileType c set makeprg=gcc\ %
au FileType cpp set makeprg=g++\ %
map <F7>:make && ./a.out<CR>
You can compile and run your program by pressing the F7 button.
您可以通过按F7按钮来编译和运行您的程序。
#10
0
It may be worth adding that SingleCompile
plugin offers that facility for C and other languages as stated by the author:
可能值得补充的是,SingleCompile插件提供了C语言和作者所说的其他语言的功能:
SingleCompile is a Vim plugin aimed at making it more convenient to compile or run a single source file without leaving Vim. Consider this situation: you have just written a small C source file for a tiny test, but you have to write a Makefile to compile it, or exit Vim to compile it, or compile it using "!gcc" without quickfix feature because Vim's make command only use the "make" command? This plugin will help you out.
SingleCompile是一个Vim插件,它的目的是使编译或运行单个源文件更方便,而不需要离开Vim。考虑这种情况:您刚刚为一个小测试编写了一个小的C源文件,但是您必须编写一个Makefile来编译它,或者退出Vim来编译它,或者使用“!”没有quickfix功能的gcc“因为Vim的make命令只使用“make”命令?这个插件可以帮助你。
Suggested mappings for F9 and F10:
F9和F10的建议映射:
nmap <F9> :SCCompile<cr>
nmap <F10> :SCCompileRun<cr>
#1
85
:!gcc -o somename % && ./somename
When using :!
, % will be substituted by the name of the currently opened file.
:!在使用时使用:!, %将被当前打开的文件的名称所替代。
When your project becomes larger, you can also write a makefile and compile the current project with :make
, if there are any errors, vim will jump to them automatically.
当您的项目变得更大时,您还可以编写一个makefile并使用:make编译当前的项目,如果有任何错误,vim将自动跳转到它们。
#2
31
Use the following mapping code in your .vimrc file for compiling and running a c programming file.
在.vimrc文件中使用以下映射代码来编译和运行c编程文件。
map <F8> : !gcc % && ./a.out <CR>
F8 key is for run the mapping. "%" is to take the current file name.
F8键用于运行映射。“%”取当前文件名。
Or, if you want to save the current file before compiling it, use
或者,如果您想在编译之前保存当前文件,请使用
map <F8> :w <CR> :!gcc % && ./a.out <CR>
Or more ideally, if you want to use the file basename not the default 'a.out' as the executable file name, use the following:
或者更理想的是,如果您希望使用文件basename而不是默认的'a '。“out”作为可执行文件名,使用以下内容:
map <F8> :w <CR> :!gcc % -o %< && ./%< <CR>
In the above command, "<" after "%" removes extension and dot (foo.c => foo), so "%<" is the file basename.
在上面的命令中,“<”在“%”之后删除扩展名和点(foo)。c => foo),所以“%<”是文件basename。
You can find this and similar infos in cmdline.txt. Command in vim:help: cmdline.txt
. You can also find specific details about the use of "%" by using :help filename-modifiers
in vim.
您可以在cmdlin .txt中找到类似的信息。在vim命令:帮助:cmdline.txt。您还可以通过使用:help fil珐琅-modifiersin vim找到有关使用“%”的具体细节。
#3
5
since most of the time you would use a Makefile, in addition to the given answers, I also like to see my results in a "cleared" screen:
由于大多数时候您会使用Makefile,除了给定的答案之外,我还希望在“清除”屏幕中看到我的结果:
map <F10> :w<CR> :!clear; make<CR> :!./%<<CR>
地图< F10 >:w < CR >:!清晰;使< CR >:! / % < < CR >
-
:w<CR>
saves the file:w < CR >保存该文件
-
:!clear; make<CR>
clears the screen and runsmake
:!清晰;使
清除屏幕并运行make -
:!./%<<CR>
runs a program (%
) without the extension (<
):!/%< CR>运行一个没有扩展名的程序(%)(<)
#4
5
TL;DR No Makefile is required, tweaking &makeprg
is also completely useless, and yet :make %<
is enough to compile from Vim.
不需要DR Makefile,调整和makeprg也完全没用,但是:make % <足以从vim编译。< p>
Long answer:
长一点的回答:
I duplicate an answer I gave in a closed "duplicate question".
我重复我在封闭的“重复问题”中给出的答案。
Considering we are using vim, and not vi, :make
is the way to go.
考虑到我们使用的是vim,而不是vi,所以:make是正确的方法。
On Linux-like (it also applies to cygwin, but not to mingw on windows -- in mingw case, see the other answers that alter &makeprg
, leave it alone otherwise) systems where gnumake is installed, if you don't have a Makefile in your project, and if your project is made of only one file, just type :make %<
. It will be enough (you can play with $CXXFLAGS
, $CFLAGS
and $LDFLAGS
to tune the compilation options). Then to run the program, type :!./%<
, or with latter versions of vim, run :terminal ./%<
.
类linux(这也适用于cygwin,但不要mingw windows——在mingw情况下,看到其他的答案改变&makeprg,别管它否则)gnumake安装系统,如果你没有一个Makefile在你的项目中,如果你的项目是由只有一个文件,只是类型:让% <。这就足够了(您可以使用$CXXFLAGS、$CFLAGS和$LDFLAGS来调整编译选项)。然后要运行程序,输入:!。/%<,或使用后版本的vim,运行:终端。/%<。
If your project is made of several files, then you'll need a Makefile to take advantage of :make
.
如果您的项目是由几个文件组成的,那么您将需要一个Makefile来利用:make。
If you manage your project with CMake, and if you compile your project in a directory (or several -> debug, release, ...) outside the sources tree, then the integration will require a plugin. AFAIK, I'm the only one to propose such a plugin: BuildToolsWrapper integrates the management of CMake (choice of the build directory, possibility to chose between the debug, or release, or whatever build directory). It has to be coupled with one of the local_vimrc plugin.
如果您使用CMake管理您的项目,并且在源代码树之外的目录(或多个-> debug, release,…)中编译您的项目,那么集成将需要一个插件。AFAIK,我是唯一一个提出这样一个插件的人:BuildToolsWrapper集成了CMake的管理(构建目录的选择,在调试中选择的可能性,或者发布,或者任何构建目录)。它必须与local_vimrc插件之一耦合。
In all cases, calling directly the compiler from within (or outside) Vim with :!g++ -o %< %
or whatever is what we used to do 15 years ago on vi. Vim has a wonderful feature: it can integrate (yes, like in IDE) the compiler. See :h quickfix
. Navigating between errors directly from the editor is much easier than extracting one error line with our eyes, typing back the line number into the editor, going back to the shell to see what exactly was rejected, ... It may be enough in C, but In C++ when we are "trying to call an overload that doesn't exist", we can't work this way (switching back and forth between the editor and the shell).
在所有情况下,直接从Vim内部(或外部)调用编译器:!g++ -o %< %或者我们15年前在vi上做的任何事情。Vim有一个很棒的特性:它可以集成(是的,就像在IDE中一样)编译器。看:h quickfix。直接从编辑器中导航错误要比用我们的眼睛提取一条错误线、将行号输入编辑器、返回shell以查看什么被拒绝要容易得多……在C语言中可能已经足够了,但是在c++语言中,当我们“试图调用一个不存在的重载”时,我们不能以这种方式工作(在编辑器和shell之间来回切换)。
Finally, if you want to compile on a single keystroke those mono-file projects, you can add in your .vimrc:
最后,如果您想要在一个击键上编译那些单文件项目,您可以添加.vimrc:
nnoremap <silent> <f7> :make %<<cr>
If you want to adapt automatically the compilation command depending of the kind of project mono-file pet project, or real world multi-file project, well, more wiring is needed, and this is what BTW does -- it reads various options to know what to do.
如果您想根据项目的单文件pet项目或真实世界的多文件项目自动调整编译命令,那么需要更多的连接,而这正是BTW所做的——它读取各种选项以知道该做什么。
Last note: &makeprg
is best left alone, at least not set to g++/gcc/clang/clang++/gfortran/... Because, every time you change your language, you'll have to change it (unless you use :setlocal
). With the solution I recommend, if I want to use clang++ instead of g++, all I have to do is to set: :let $CXX='clang++'
(or $CC
in C), and then call :make %<
. I can even define :let $CXXFLAGS='-std=c++11'
to compile in C++11 -- the same variable will be used to turn warnings on, to use a sanitizer, etc.
最后注意:&makeprg最好不要使用,至少不要设置为g++/gcc/clang/clang++/gfortran/…因为,每次您更改语言时,都必须更改它(除非您使用:setlocal)。对于我推荐的解决方案,如果我想使用clang+而不是g++,我只需设置:::让$CXX='clang++'(或$CC in C),然后调用:make %<。我甚至可以定义:让$CXXFLAGS='-std=c++11'编译在c++11中——相同的变量将被用来打开警告,使用消毒器等等。
#5
4
Add this line in your vimrc
file
在vimrc文件中添加这一行
nnoremap <silent> <F8> :!clear;gcc % -o % && ./%<CR>
Now you only have to press f8 key to compile and run your c program.
现在,您只需按f8键编译并运行您的c程序。
#6
2
Just thought I would add this to these answers here. As has been mentioned, you can use the :make
command in vim. What has not been mentioned yet, is that :make
can invoke other programs, other than make
.
我只是想把这个加到这些答案中。如前所述,您可以在vim中使用:make命令。还没有提到的是:make可以调用除make之外的其他程序。
:set makeprg=gcc\ %
Will cause :make
to execute gcc
with the %
symbol replaced by the current file name.
将导致:使以当前文件名替换的%符号执行gcc。
You can then get fancy and do
然后你就可以开始幻想了。
:set makeprg=gcc\ %\ &&\ ./a.out
and simply typing :make
will compile and execute your program. You can do this for other languages as well of course.
简单地输入:make将编译并执行您的程序。当然,对于其他语言也可以这样做。
:set makeprg=cabal\ repl
:set makeprg=python\ %
#7
1
After doing some research (including this very page), I made my mind to add this shortcut:
在做了一些研究(包括这一页)之后,我决定添加这个快捷方式:
map <F9> :w<CR> :!gcc % -o %<.x -Wall -Wextra 2>errors.err; cat errors.err<CR>
You can also include -ansi -pedantic-errors
if you will.
如果您愿意,您还可以包含-ansi - pedanmy错误。
The errors.err
file will help you with vi quickfix.
的错误。err文件将帮助您处理vi quickfix。
#8
1
It's 2018 now, vim 8 has released for 2 years and shipped with all the Linux distributions and Mac OS X. But a lot of vim tutorials are still teaching people something ten years ago.
现在已经是2018年了,vim 8已经发布了2年,并随所有Linux发行版和Mac OS x一起发布。
You can compile your C++/Java programs in vim as convenience as Sublime Text or NotePad++ with some dedicated plugins for Vim 8 or NeoVim.
你可以在vim中编译你的c++ /Java程序,因为它可以像卓越的文本或NotePad++那样使用一些专用的vim 8或NeoVim插件。
For example, the AsyncRun plugin will allow you run shell commands in background and read output from quickfix window in realtime. See the screen capture.
例如,AsyncRun插件允许你在后台运行shell命令并实时读取quickfix窗口的输出。看到屏幕截图所示。
Just like compiling programs in IDEs, the compilation errors will be matched by errorformat and be highlighted and become selectable. You can navigate errors in the quickfix window or continue editing while compiling.
就像在ide中编译程序一样,编译错误将与errorformat匹配,并被突出显示并成为可选择的。您可以在quickfix窗口中导航错误,或者在编译时继续编辑。
Quick setup
快速设置
Copy & paste the lines below to your vimrc:
复制并粘贴下面的行到您的vimrc:
Plug 'skywind3000/asyncrun.vim'
" open quickfix window automatically when AsyncRun is executed
" set the quickfix window 6 lines height.
let g:asyncrun_open = 6
" ring the bell to notify you job finished
let g:asyncrun_bell = 1
" F10 to toggle quickfix window
nnoremap <F10> :call asyncrun#quickfix_toggle(6)<cr>
When you input “:AsyncRun echo hello ” in the command line:
当您在命令行输入“:AsyncRun echo hello”时:
看到这里的捕获
You will see the realtime command output in the open quickfix window.
您将在open quickfix窗口中看到实时命令输出。
Compile and run a single file
编译并运行一个文件
Compiling a single file with AsyncRun is much simpler than Sublime Text’s build system. We can setup F9 for this:
用AsyncRun编译一个文件要比编写一个优秀的文本构建系统简单得多。我们可以为此设置F9:
noremap <silent> <F9> :AsyncRun gcc -Wall -O2 "$(VIM_FILEPATH)" -o "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>
The macros in $(..)
form will be expanded as the real file name or directory, and then we will have F5 to run the executable:
$(.. .)表单中的宏将扩展为实际文件名或目录,然后我们将有F5运行可执行文件:
noremap <silent> <F5> :AsyncRun -raw -cwd=$(VIM_FILEDIR) "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>
The double quotation mark is used to handle path names containing spaces. The option -cwd=$(VIM_FILEDIR)
means running the file in the file's directory. The absolute path name $(VIM_FILEDIR)/$(VIM_FILENOEXT)
is used because linux needs a ./
prefix to running executables in current directory, but windows doesn't . Using the absolute path name of the binary file can handle this crossing platform issue.
双引号用于处理包含空格的路径名。选项-cwd=$(VIM_FILEDIR)表示在文件的目录中运行文件。使用绝对路径名$(VIM_FILEDIR)/$(VIM_FILENOEXT)是因为linux需要一个./前缀来运行当前目录中的可执行文件,但windows不需要。使用二进制文件的绝对路径名可以处理这个交叉平台问题。
Another option -raw
means the output will not be matched by vim's errorformat, and will be displayed in quickfix as what it is. Now you can compile your file with F9, check the compilation errors in quickfix window and press F5 to run the binary.
另一个选项-raw意味着输出将不会被vim的errorformat匹配,并将显示在quickfix中。现在可以使用F9编译文件,检查quickfix窗口中的编译错误,并按F5运行二进制文件。
Build C/C++ Projects
构建C / c++项目
No matter what build tool you are using, make or cmake, project building means acting to a group of files. It requires locating the project root directory. AsyncRun uses a simple method called root markers to identify the project root. The Project Root is identified as the nearest ancestor directory of the current file which contains one of these directories or files:
无论您使用什么构建工具、make还是cmake,项目构建都意味着对一组文件进行操作。它需要定位项目根目录。AsyncRun使用一种简单的方法,称为根标记来标识项目根。项目根目录被标识为当前文件中最近的祖先目录,其中包含以下目录或文件:
let g:asyncrun_rootmarks = ['.svn', '.git', '.root', '_darcs']
If none of the parent directories contains these root markers, the directory of the current file is used as the project root. This enables us to use either <root>
or $(VIM_ROOT)
to represent the project root. and F7 can be setup to build the current project:
如果任何父目录都不包含这些根标记,则将当前文件的目录用作项目根。这使我们可以使用
noremap <silent> <F7> :AsyncRun -cwd=<root> make <cr>
What if your current project is not in any git or subversion repository ? How to find out where is my project root ? The solution is very simple, just put an empty .root file in your project root, it will be located easily.
如果当前项目不在任何git或subversion存储库中,该怎么办?如何找到我的项目根目录?解决方案非常简单,只需在项目根中放入一个空的.root文件,就可以轻松地找到它。
Let’s move on, setup F8 to run the current project:
让我们继续,安装F8以运行当前项目:
noremap <silent> <F8> :AsyncRun -cwd=<root> -raw make run <cr>
The project will run in its root directory. Of course, you need define the run rule in your own makefile. then remap F6 to test:
该项目将在其根目录中运行。当然,您需要在自己的makefile中定义运行规则。然后将F6重新映射到测试:
noremap <silent> <F6> :AsyncRun -cwd=<root> -raw make test <cr>
If you are using cmake, F4 can be map to update your Makefile:
如果您正在使用cmake,可以使用F4来更新您的Makefile:
nnoremap <silent> <F4> :AsyncRun -cwd=<root> cmake . <cr>
Due to the implementation of c runtime, if the process is running is a non-tty environment, all the data in stdout will be buffered until process exits. So, there must be a fflush(stdout)
after your printf
statement if you want to see the real-time output. or you can close the stdout buffer at the beginning by
由于c运行时的实现,如果进程运行的是一个非tty的环境,那么stdout中的所有数据将被缓冲,直到进程退出。因此,如果您希望看到实时输出,那么在printf语句之后必须有一个fflush(stdout)。或者您可以在开始时关闭stdout缓冲区
setbuf(stdout, NULL);
At the mean time, if you are writing C++ code, a std::endl can be appended to the end of std::cout. It can force flush the stdout buffer. If you are developing on windows, AsyncRun can open a new cmd window for the child process:
同时,如果您正在编写c++代码,那么std::endl可以附加到std::cout的末尾。它可以强制刷新stdout缓冲区。如果您正在windows上开发,AsyncRun可以为子进程打开一个新的cmd窗口:
nnoremap <silent> <F5> :AsyncRun -cwd=$(VIM_FILEDIR) -mode=4 "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>
nnoremap <silent> <F8> :AsyncRun -cwd=<root> -mode=4 make run <cr>
Using the option -mode=4
on windows will open a new prompt window to run the command, just like running command line programs in Visual Studio. Finally, we have these key mappings below:
在windows上使用选项-mode=4将打开一个新的提示窗口来运行命令,就像在Visual Studio中运行命令行程序一样。最后,我们有以下关键映射:
- F4: update Makefile with cmake.
- F4:用cmake更新Makefile。
- F5: run the single file
- F5:运行单个文件
- F6: run project test
- F6:运行测试项目
- F7: build project
- F7:建设项目
- F8: run project
- F8:运行项目
- F9: compile the single file
- F9:编译单个文件
- F10: toggle quickfix window
- F10:切换quickfix窗口
It is more like build system in NotePad++ and GEdit. If you are using cmake heavily, you can write a simple shell script located in ~/.vim/script/build.sh
to combine F4 and F7 together: it will update Makefile if CMakeList.txt has been changed, then exectute make.
它更像是记事本++和GEdit中的构建系统。如果大量使用cmake,可以编写位于~/.vim/script/build中的简单shell脚本。sh将F4和F7合并在一起:它将更新Makefile if CMakeList。txt已经更改,然后执行。
Advanced usage
高级用法
You can also define shell scripts in your dotfiles repository and execute the script with F3:
您还可以在您的dotfiles存储库中定义shell脚本,并使用F3执行脚本:
nnoremap <F3> :AsyncRun -cwd=<root> sh /path/to/your/dotfiles/script/build_advanced.sh <cr>
The following shell environment variables are defined by AsyncRun:
异步调用定义了以下shell环境变量:
$VIM_FILEPATH - File name of current buffer with full path
$VIM_FILENAME - File name of current buffer without path
$VIM_FILEDIR - Full path of current buffer without the file name
$VIM_FILEEXT - File extension of current buffer
$VIM_FILENOEXT - File name of current buffer without path and extension
$VIM_CWD - Current directory
$VIM_RELDIR - File path relativize to current directory
$VIM_RELNAME - File name relativize to current directory
$VIM_ROOT - Project root directory
$VIM_CWORD - Current word under cursor
$VIM_CFILE - Current filename under cursor
$VIM_GUI - Is running under gui ?
$VIM_VERSION - Value of v:version
$VIM_COLUMNS - How many columns in vim's screen
$VIM_LINES - How many lines in vim's screen
$VIM_SVRNAME - Value of v:servername for +clientserver usage
All the above environment variables can be used in your build_advanced.sh
. Using the external shell script file can do more complex work then a single command.
可以在build_advanced.sh中使用上述所有环境变量。使用外部shell脚本文件可以完成比单个命令更复杂的工作。
Grep symbols
Grep的符号
Sometimes, If you don't have a well setup environment in you remote linux box, grep is the most cheap way to search symbol definition and references among sources. Now we will have F2 to search keyword under cursor:
有时,如果您在远程linux box中没有良好的设置环境,那么grep是在源文件中搜索符号定义和引用的最廉价的方法。现在我们有F2在光标下面搜索关键字:
if has('win32') || has('win64')
noremap <F2> :AsyncRun! -cwd=<root> grep -n -s -R <C-R><C-W> --include='*.h' --include='*.c*' '<root>' <cr>
else
noremap <F2> :AsyncRun! -cwd=<root> findstr /n /s /C:"<C-R><C-W>" "\%CD\%\*.h" "\%CD\%\*.c*" <cr>
endif
The above script will run grep or findstr in your project root directory, and find symbols in only .c
, .cpp
and .h
files. Now we move around the cursor and press F2, the symbol references in current project will be displayed in the quickfix window immediately.
上面的脚本将在项目根目录中运行grep或findstr,并且只在.c、.cpp和.h文件中找到符号。现在我们移动光标并按F2,当前项目中的符号引用将立即显示在quickfix窗口中。
This simple keymap is enough for most time. And you can improve this script to support more file types or other grep tools in your vimrc .
这个简单的关键图在大多数情况下都足够了。您可以改进此脚本,以便在vimrc中支持更多的文件类型或其他grep工具。
That’s the practical way to build/run C/C++ projects in Vim 8 or NeoVim. Just like Sublime Text’s build system and NotePad++’s NppExec.
这是在vim8或NeoVim中构建/运行C/ c++项目的实用方法。就像崇高的文本构建系统和记事本+的NppExec。
No more outdated vim tutorials again, try something new.
不再有过时的vim教程,尝试一些新的东西。
#9
0
Add these three lines to your .vimrc
file
将这三行添加到.vimrc文件中
au FileType c set makeprg=gcc\ %
au FileType cpp set makeprg=g++\ %
map <F7>:make && ./a.out<CR>
You can compile and run your program by pressing the F7 button.
您可以通过按F7按钮来编译和运行您的程序。
#10
0
It may be worth adding that SingleCompile
plugin offers that facility for C and other languages as stated by the author:
可能值得补充的是,SingleCompile插件提供了C语言和作者所说的其他语言的功能:
SingleCompile is a Vim plugin aimed at making it more convenient to compile or run a single source file without leaving Vim. Consider this situation: you have just written a small C source file for a tiny test, but you have to write a Makefile to compile it, or exit Vim to compile it, or compile it using "!gcc" without quickfix feature because Vim's make command only use the "make" command? This plugin will help you out.
SingleCompile是一个Vim插件,它的目的是使编译或运行单个源文件更方便,而不需要离开Vim。考虑这种情况:您刚刚为一个小测试编写了一个小的C源文件,但是您必须编写一个Makefile来编译它,或者退出Vim来编译它,或者使用“!”没有quickfix功能的gcc“因为Vim的make命令只使用“make”命令?这个插件可以帮助你。
Suggested mappings for F9 and F10:
F9和F10的建议映射:
nmap <F9> :SCCompile<cr>
nmap <F10> :SCCompileRun<cr>