Search code examples
bashvisual-studio-codegnome-terminalgeanyvscode-keybinding

How to add the custom compile commands in VS Code?


I usually do competitive programming in Geany IDE and have the following custom compile command to compile C++ programs -

g++ -std=c++17 -Wshadow -Wall -o "%e" "%f" -g -fsanitize=address -fsanitize=undefined -D_GLIBCXX_DEBUG

The compile command is binded by f9 key. I just have to press f9, which saves and compiles the file and then I switch to bash terminal (f2 key shortcut) to execute the binary file. The terminal also follows the path of the current file opened in editor.

I want the same settings in VS Code. So far, I have managed to bring the editor and terminal side by side and to easily toggle the focus between them via f1 and f2.

But I am unable to set the custom compile command, bind it with f9 key and to configure the terminal so that it follows the path of file in editor currently in focus.
Please give me a complete solution. It would be much better to edit the json setting files directly.
Here is a snapshot of the settings in my Geany IDE :- This is how my Geany looks and the Setting boxes


Solution

  • You can set a custom task in VS Code. Edit the tasks.json file in the .vscode folder of your workspace like:

    {
        "version": "2.0.0",
        "tasks": [
            {
                "label": "My build task",
                "type": "shell",
                // Assign output file name with VSCode inner variables like ${fileBasename}
                "command": "g++ -std=c++17 -Wshadow -Wall -o ${fileBasename} -g -fsanitize=address -fsanitize=undefined -D_GLIBCXX_DEBUG",
                "options": {
                },
                "problemMatcher": ["$gcc"],
                "group": {
                    "kind": "build",
                    "isDefault": true
                }
            }
        ]
    }
    

    You can write the compile command directly into "command" attribute, or write it with more commands into a script then write the simple executing script command in the attribute instead.

    And the "isDefault": true attribute make this default task which could be invoked simply binding with ctrl+shift+B.