Search code examples
c++cvisual-studio-codecompilation

How to compile on save (watch) C or C++ files in VS Code?


I was wondering if there is a recommended way to watch the .c and .h files in a project and watch them so they get compiled when there are any changes.

I have the C/C++ extension installed and I can compile manually, but I'm surprised there's no way to do it automatically (is it a bad idea?).

I guess I could write my own watcher script, but I was wondering if there is a better way to do it that I've missed.


Solution

  • I'm going to assume you mean building the program that the source file being saved contributes code to, instead of just compiling that single source file into object form, since I don't see why that would be useful.

    First of all, there are a multitude of ways to do builds of C or C++ programs in VS Code. That includes build tasks, CMake Tools, Makefile Tools, or just running build commands manually in the terminal (and the multitude of different ways there are to do that), and Code Runner (but I suggest not to use that).

    To answer the question as it was asked: No. I don't know of an easy way to make builds happen on save- for any of the build methods I listed above.

    But you can quite easily turn this around from a push model to a pull model- that is- configure files to be saved before running build when invoking build:

    • For CMake Tools, use the cmake.saveBeforeBuild setting. There's even cmake.buildBeforeRun.
    • For Makefile Tools, use its makefile.saveBeforeBuild setting. There's even makefile.buildBeforeLaunch.
    • For build tasks, use VS Code's builtin task.saveBeforeRun setting. If you use a launch config to run, you can also set up your build task to run before launch by using the launch config's preLaunchTask property.
    • For running commands manually in a terminal, it's not as direct. You could write a keybinding with runCommands that first saves all files and then sends your build commands to an integrated terminal.
    • For Code Runner, use its code-runner.saveAllFilesBeforeRun setting.

    If you're looking for something for quick and small-scale experimentation instead of larger projects, see also Is there a continuous compilation plugin for Visual Studio Code like Godbolt's Compiler Explorer?.


    I'm surprised there's no way to do it automatically (is it a bad idea?).

    I'd argue the pull model is better than compiling an entire program whenever any of its source files get saved. C and C++ project builds can get quite computationally expensive, and if you have multiple files, you're going to be putting unnecessary load on your machine as you individually save each file you've changed.