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
You can use % to reference the current file
so:
:!g++ %
in VIM "%:p" stands for the current file.
try "!g++ %:p"
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!
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
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>
Related
I've recently installed a vim editor in my Windows operating system.
I only know the conventional procedure i.e, creating the source file in the editor and running it from the command line. But,
I don't quite understand how to compile a CPP program directly from the vim editor.
when I run the command
:!g++ hello.cpp -o hello
from the vim command line, I get the following message
C:\WINDOWS\system32\cmd.exe /c (g++ hello.cpp -o hello)
Hit any key to close this window...
I assume your version of Vim is windows version and not cygwin version.
First you need to install a compiler, and make sure it's in your PATH.
Also, read the documentation about quickfix window as this is the integrated vim way of compiling. :!make or :!g++ ... are not the way to go.
MSVC
I don't suppose this is the compiler you have as I expect you'd have used Visual Studio in that case. Anyway, IIRC, there is a msdev compiler plugin you could load with :compiler msdev, then you should able to run :make.
Don't hesitate to complete my answer if you see errors.
g++ through cygwin
There is a big advantage: gnumake is properly configured: in the console you could run make foo, and if you have foo.cpp or foo.c and no Makefile in the current directory, this would compile the monofile project. In all cases, a Makefile is fine; and it's required with multiple source files.
The big problem: pathnames are not expressed in the same way. They need to be translated. I provide a way to do that in my Build-Tools-Wrapper plugin. Just execute :BTW add cygwin.
Then from vim, again type :make %<. That will translate into :make foo (assuming you're editing foo.cpp), which translates into make fooshell wise, which translates into $CXX $CPPFLAGS $CXXFLAGS $LDFLAGS foo.cpp -o foo $LDLIBS (or something like that).
Note: this means the options can be tweaked with: :let $CXXFLAGS = '-std=c++17 -Wall -Wextra'
BTW, if you have my build-tools-wrapper plugin, you can execute directly :Make instead of :make %<, or just <F5>directly, IIRC.
g++ through mingw
The good news: no need to translate pathnames
The bad news, gnumake isn't correctly configured. This means that in the console make foo won't work. And consequently, this won't work from Vim.
This time, you'll either need a Makefile, or you'll need to tweak 'makeprg' setting. Like for instance :let &makeprg = 'g++ -Wall -Wextra -std=c++17 -o %< %' and then type simply :make.
As you already know, we can see 'make -k' command when we execute 'M-x compile' in emacs c++ mode.
But, now I'm studying some boost libraries, so I must frequently compile just single file after writing a example code.
So, for convenience, I've been doing this like below.
(1) make an alias in shell init file for g++ compile command.
alias c="g++ -g -Wall -O0 -std=c++11"
(2) map 'M-x compile' command to Function Key F9 in .emacs
(global-set-key [f9] 'compile)
(3) write c++ code
(4) press F9 and modify filename to current open file
For example, you can see 'Compile command: c vvv.cpp' in the below screen shot.
(This screen shot is just a simple code that I made for this question.
'c' is alias for compile command and options)
But, this open filename is actually 'vector1.cpp', so 'vvv.cpp' should be automatically replaced by 'vector1.cpp'.
I think this is not bad.
But, I'd like to find a way that I don't have to modify the current filename.
"Just press F9 and RET, then the current file will be compiled." This is exactly what I want.
Is there any better idea or way I can do like this?
Or plz let me know your nice compiling way for a minimal key pressing.
Thanks.
The EmacsWiki has a nice section explaining how you can customize the compile command: Compile Command
In your case, you could add a hook to the c++ mode to define the compile-command variable as you need. Following the example on the wiki:
(add-hook 'c++-mode-hook
(lambda ()
(set (make-local-variable 'compile-command)
(format "g++ -g -Wall -O0 -std=c++11 %s" (buffer-name)))))
Adding this snippet to your .emacs should do the trick.
I've written a simple c++ program on Xcode, all contained within ONE FILE called huffmanGenerator.cpp. The program reads input from a file on the user's computer, and writes output to a file saved to their computer.
The instructor has asked us to create a makefile so that our programs compile and run with g++ OR gcc in Linux; however she never showed us how to do so, and when the class asked for help, her answer was we could figure it out.
I found many links online, but they're all very confusing as this is all new to me, and most of them fail to answer even the most basic questions like what kind of file should the makefile be? Is it a .txt? Should I just save one in word?
Please help do what the instructor won't, enlighten me. Thanks!
what kind of file should the makefile be?
It should be a plaintext file called Makefile or makefile. The reason the name matters is because when you run the make command, it looks for a file with this name by default for directions on how to compile your code. You can also name it whatever you want as long as you specify the name when you run it (make -f filename).
Is it a .txt?
No, it has no extension. Extensions don't mean that much in *nix.
Should I just save one in word? (Assume you mean Microsoft Word.)
No, definitely not. Whitespace (tabs/spaces/new lines) have meaning in these files, so you should use an editor that won't add formatting to the file. Something like pico/vi/etc.
Here is an example of a makefile, that I think does what you are asking.
# You can change your compiler to gcc / g++ here.
CC=g++
# Add whatever flags you want to use here.
CFLAGS=-c -Wall
all:
$(CC) $(CFLAGS) huffmanGenerator.cpp -o huffmanGenerator
#Use something like this to run `make clean` which deletes your object files, so you can do a fresh compile.
#clean:
# rm -rf *o huffmanGenerator
As a side note, you would be served well not to blame your professor for not spelling out everything for you. When you graduate, you will often be given tasks that have no other directions than a set of requirements and a deadline. You will need to figure it out. You could have easily made this make file by visiting http://mrbook.org/tutorials/make/ (search google for 'makefile tutorial').
The makefile should be called Makefile. It is just a text file.
You need a text editor. There are many to choose from, vim, emacs, nano, pico, ..., etc.
Open a command line and run, say
$ pico Makefile
Then you would enter the contents of the Makefile
all:
g++ -o huffmanGenerator huffmanGenerator.cpp
Save and exit and run make
$ make
I'd like to compile cpp file w/o turning off vi.
I know the :!g++ file.cpp but I prefer :make so I added this line in .vimrc file
au FileType C set makeprg=gcc\ %
au FileType Cpp set makeprg=g++\ %
but I keep getting
"make: ***** No targets specified and no makefile found. Stop.** "message.
can anyone tell me what is wrong with my setting?
I use to compile successfully with the option above.
You need the substitution there, try something like:
set makeprg=gmake\ %:r.o
Oh, this assumes that you've got:
a (M|m)akefile in the directory, or
default SUFFIX rules are available for your environment (which it looks like there aren't)
Check for the default by entering:
make -n <my_file>.o
and see if that gives you something sensible.
If there is a makefile in another location you can add the -f option to point at the makefile, for example:
set makeprg=gmake\ -f\ ../some_other_dir/makefile\ %:r.o
BTW For learning about make, and especially gmake, I'd suggest having a look at the excellent book "Managing Projects with GNU Make" (sanitised Amazon link).
HTH.
cheers
I should change C,Cpp into c,cpp, then it works fine.
thank you all, especially Rob Wells, your answer helped me a lot. thank you.
I think it's much easier if you write a Makefile and put it where vi can find it. I'm not sure if you actually use vi (I've only used Vim), but when there is a Makefile compiling should be as easy as writing :make (no set makeprg needed).
It can be easily achieved by the use of key maps.
First open up your vimrc file and these lines to the file,
autocmd filetype cpp nnoremap <F4> :!g++ % -ggdb -o %:r <CR>
autocmd filetype cpp nnoremap<F5> :!g++ % -ggdb -o %:r && ./%:r <CR>
The first line maps the key F4 to compiling the file. The second line maps the key F5 to compile and run.
If you use gdb frequently then this may also come handy.
autocmd filetype cpp nnoremap<F10> :!g++ % -ggdb -o %:r && gdb -tui %:r <CR>
This line maps the key F10 to compile and start gdb
Hope this helps.
I recommend a vim plugin called SingleCompile instead of what you have done:
http://www.vim.org/scripts/script.php?script_id=3115
First of all, just make the bloody make file. Every tool out there is expecting to work with make and if your compilations are that simple it takes about 30 seconds to write a make file that compiles all c and cpp files into an executable.
Second, if you refuse to use a make file then try
:help system
That should give you enough info to come up with your own command similar to this
:com Mymake call system("g++ ".expand("%"))
How can I compile/run C or C++ code in a Unix console or a Mac terminal?
If it is a simple single-source program,
make foo
where the source file is foo.c, foo.cpp, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension.
Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in $PATH to find executables, and most often that does not include the current directory (.).
So to run the built executable foo:
./foo
gcc main.cpp -o main.out
./main.out
This is the command that works on all Unix machines... I use it on Linux/Ubuntu, but it works in OS X as well. Type the following command in Terminal.app.
g++ -o lab21 iterative.cpp
-o is the letter O, not zero
lab21 will be your executable file
iterative.cpp is your C++ file
After you run that command, type the following in the terminal to run your program:
./lab21
Two steps for me:
First:
make foo
Then:
./foo
All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.
You can display this path in the terminal with this command:
echo $PATH
On Mac OS X (by default) this will display the following colon separated search path:
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
So any executable in the listed directories can by run just by typing in their name. For example:
cat mytextfile.txt
This runs /bin/cat and displays mytextfile.txt to the terminal.
To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:
/Users/oliver/MyProgram
If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:
MyProject/MyProgram
Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:
../MyProject/MyProgram
Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:
./MyProgram
To determine which directory you are currently in use the pwd command.
If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.
This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:
#!/bin/sh
export PATH=$PATH:~/bin
Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:
export PATH=~/bin:$PATH
Do all of this in "Terminal".
To use the G++ compiler, you need to do this:
Navigate to the directory in which you stored the *.cpp file.
cd ~/programs/myprograms/
(the ~ is a shortcut for your home, i.e. /Users/Ryan/programs/myprograms/, replace with the location you actually used.)
Compile it
g++ input.cpp -o output.bin (output.bin can be anything with any extension, really. Extension .bin is just common on Unix.)
There should be nothing returned if it was successful, and that is okay. Generally you get returns on failures.
However, if you type ls, you will see the list of files in the same directory. For example, you would see the other folders, input.cpp and output.bin
From inside the directory, now execute it with ./outbut.bin
A compact way to go about doing that could be:
make foo && ./$_
It is nice to have a one-liner so you can just rerun your executable again easily.
Assuming the current directory is not in the path, the syntax is ./[name of the program].
For example ./a.out
To compile C or C++ programs, there is a common command:
make filename
./filename
make will build your source file into an executable file with the same name. But if you want to use the standard way, You could use the gcc compiler to build C programs and g++ for C++.
For C:
gcc filename.c
./a.out
For C++:
g++ filename.cpp
./a.out
Add the following to get the best warnings, and you will not regret it. If you can, compile using WISE (warning is error).
- Wall -pedantic -Weffc++ -Werror
Step 1 - create a cpp file using the command
touch test.cpp
Step 2 - Run this command
g++ test.cpp
Step 3 - Run your cpp file
./a.out
I am on a new MacBook Pro with the Apple M1 Pro chip. I have my Xcode installed - both IDE and command line tools. This is how it worked for me:
g++ one.cpp -o one
./one
Use a makefile. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.
Read the make manual. It seems quite long at first glance, but most sections you can just skim over. All in all, it took me a few hours and made me much more productive.
I found this link with directions:
http://www.wesg.ca/2007/11/how-to-write-and-compile-c-programs-on-mac-os-x/
Basically you do:
gcc hello.c
./a.out (or with the output file of the first command)
In order to compile and run C++ source code from a Mac terminal, one needs to do the following:
If the path of .cpp file is somePath/fileName.cpp, first go the directory with path somePath
To compile fileName.cpp, type c++ fileName.cpp -o fileName
To run the program, type ./fileName
Just enter in the directory in which your .c/.cpp file is.
For compiling and running C code.
gcc filename.c
./a.out filename.c
For compiling and running C++ code.
g++ filename.cpp
./a.out filename.cpp
You need to go into the folder where you have saved your file.
To compile the code: gcc fileName
You can also use the g++ fileName
This will compile your code and create a binary.
Now look for the binary in the same folder and run it.
For running C++ files, run the below command, assuming the file name is "main.cpp".
Compile to make an object file from C++ file.
g++ -c main.cpp -o main.o
Since #include <conio.h> is not supported on macOS, we should use its alternative which is supported on Mac. That is #include <curses.h>. Now the object file needs to be converted to an executable file. To use file curses.h, we have to use library -lcurses.
g++ -o main main.o -lcurses
Now run the executable.
./main
Running a .C file using the terminal is a two-step process.
The first step is to type gcc in the terminal and drop the .C file to the terminal, and then press Enter:
gcc /Desktop/test.c
In the second step, run the following command:
~/a.out