tags:

views:

169

answers:

5

Sometimes I run make directly from the vim command line. However, sometimes I would just like to build one file currently being edited: !g++ filename.cpp . Is there a shortcut to reference the file without having to type it..?

Guys, I DO NOT want to use make at all. all I want to do is to build it from vi's command line, using g++/gcc

+2  A: 

in VIM "%:p" stands for the current file.

try "!g++ %:p"

Emmanuel Caradec
what is point of p?
vehomzzz
It expand to the full path from root. I got used to it because I was typing something that lose the root. Its not required here, I typed the response fast, but Peter answer is the best.
Emmanuel Caradec
+8  A: 

You can use % to reference the current file so:

:!g++ %
Peter van der Heijden
+2  A: 

You can use this to refer to the filename you are working on with the extension substituted with .o:

%r.o

Your filename.cpp becomes filename.o which is useful if you put something like this in your .vimrc.:

set makeprg=gmake\ %:r.o

That way you can just do this in vim and it will then launch the command declared using makeprg on the current file:

:make
Rob Wells
Can you explain the colon in '%:r.o' (or the absence of the colon previously)?
Jonathan Leffler
see `:help filename-modifiers`
rampion
+2  A: 

If your make program is actually GNU make, just execute:

:make %<

If you want to add flags like -Wall or -pedantic then just set $CFLAG (for compiling C files, or $CPPFLAGS for C++ files), or if you want to specify libraries then set $LDFLAGS from vim.

:h :make
:h %<

EDIT: Unlike plain calls to :!gcc, this solution is compatible with the quickfix mode (:h quickfix), and it does not require to change &makeprg to 'g++ $CPPFLAGS -o $* $*.cpp $LDFLAGS'.

NB:

  • No need to write any makefile to take advantage of GNU-make.
  • And even if you have one Makefile, and as long as you don't mess with the default implicit rules, this solution will also work!
Luc Hermitte
I DO NOT want to use make at all. all I want to do is to build it from using g++/gcc
vehomzzz
You missed the point there is no need to write any makefile, and that GNU-make will call gcc or g++ by himself without us to tell him to do so.
Luc Hermitte
+1 ..thanks for explaining :))))
vehomzzz
What will make %< generate? a.out or filename (executable)? what is the point of < ? thanks.
vehomzzz
%< is % without the extension. It tells make to generate the executable with no extension (unless under windows as it is implicit there)
Luc Hermitte
+1  A: 

As mentioned the shortcut is %.

You can bind the whole thing to one key by putting the following in your .vimrc file:

map <F9> :!gcc %<CR>
carlosdc