CD86
CD86

Reputation: 1079

make from within vim

I am using gvim for coding c++. Since my program involves cmake, my sources are located in a different directory than my build.

How can I still invoke :make from within vim so that the correct make file within the build directory is found?

how can I then subsequently start my application with the very same command line style and one keystroke?

Upvotes: 1

Views: 3260

Answers (3)

CyberC4p0
CyberC4p0

Reputation: 1

You can use the following:

autocmd filetype cpp nnoremap <F8> :w<CR> :!clear<CR> :!make && ./%<<CR>

This will allow you to Compile/Run C++ using Makefile with <F8> and clear console

Upvotes: 0

Luc Hermitte
Luc Hermitte

Reputation: 32926

TD;LR: just assign 'cd "compi/dir" && make $*' to &makeprg (with :let) and run :make youroptionaltarget -j 4.

In another Q/A, I've already criticised the :!make approach. This is what we had to do 20-ish years ago with vi. Vim has introduced integrated compilation through quickfix mode. Please learn vim way to compile code.

In CMake case, we can indeed compile with cmake --someoption compil/dir. I use it when I compile with VC++ compiler, piloted by CMake, from vim. The rest of the time, I'd rather avoid it as it messes compiler outputs by prepending each line with number>, which breaks vim quickfix feature. Unfortunately there is no neat way to ignore this noise by tweaking &errorformat. So far I postprocess cmake and ctest outputs to remove ^\d+>.

So. What can, and shall, we really do? We should take advantage of vim quickfix feature. This is done by tweaking &makeprg and &efm options. In your case, the first one should be enough. Use it to change directory and execute make. And finally compile with :make and navigate errors with :cn, :cp, :cc, etc.

If you want also to compile in background, you'll need a plugin that knows how to compile in background in a directory which is not the current one. This is where I advertise my build-tool-wrappers plugin that provides these features and a few more CMake related features.

PS: It's also possible to use make (and ninja) -c parameter.

Upvotes: 3

oLen
oLen

Reputation: 5547

The easiest solution I came up with is the following:

:! (cd /path/to/your/cmake/build/directory; make)

To execute the program at the same time, you can append commands with ; or &&:

:! (cd /path/to/your/cmake/build/directory; make && ./myProgram)

In this page, you can find a tutorial how to bind this in order to do this in one key stroke.

Explanation:

In vim, you can execute any command with :! command (for instance, :! ls). With (cd [...]; [...]), you specify that the execution directory is different by creating a subshell and changing to this directory in the subshell.

Upvotes: 0

Related Questions