Rockstar5645
Rockstar5645

Reputation: 4516

How to compile and run a c++ source file in visual studio code

I've searched for an answer to this question, but couldn't seem to find one. I know that we can use task.json files to automate the build process. But I want to use Visual Studio Code to implement algorithms in C++ for competitive programming. I want to be able to compile a program, and run it all in one go, if there aren't any errors. If there are errors, I would like them to be displayed.

Also, visual studio code comes with an integrated terminal, so it would be nice if the program output could be redirected there. Also, how can we map a keyboard shortcut to run this task.

I'm using Visual Studio Code 2019 on Windows 10 with the MinGW G++ compiler.

EDIT

I've tried Escape0707's answer below, and I tried executing 'Run Code' with the default key binding of Ctrl + Alt + N but I'm getting this error.

enter image description here

Upvotes: 5

Views: 9776

Answers (2)

Escape0707
Escape0707

Reputation: 152

Updated method which combines make and vscode-cpptools debug:

If you don't care about VSCode integrated debugging tools, which will give you the ability to set breakpoints, change variable value during runtime, inspect variable value, and etc, and you want a somewhat easier, simpler, faster, transparent way to invoke the good old command line tools, skip this section and checkout Code Runner below.

The default configurations come with VSCode C++ extension are kind of slow for low-end machines. The worst part is that they will always rebuild your executable, and don't support 'Start Without Debugging'. Below is a workaround for Linux (and of course remote-WSL).

To address the first issue, you setup make (for simple one source file compiling you only need to install make) to build your source codes, and setup the build task in tasks.json. To address the second issue, you create another task just to run the built executable after the first task finished:

Use Intellisense to learn about each properties in configs.

tasks.json

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "presentation": {
    "clear": true,
    "focus": true,
    "panel": "shared"
  },
  "tasks": [
    {
      "label": "make active file",
      "type": "shell",
      "command": "make",
      "args": ["${fileBasenameNoExtension}.out"],
      "problemMatcher": "$gcc",
      "group": {
        "kind": "build",
        "isDefault": true
      }
    },
    {
      "label": "run active file executable without debuging",
      "type": "shell",
      "command": "${fileDirname}/${fileBasenameNoExtension}.out",
      "presentation": {
        "clear": false
      }
    },
    {
      "label": "make and run active file without debuging",
      "group": {
        "kind": "test",
        "isDefault": true
      },
      "dependsOn": [
        "make active file",
        "run active file executable without debuging"
      ],
      "dependsOrder": "sequence"
    }
  ]
}

To enable debugging using VSCode in this way, first make sure you added -g compile flag to CXXFLAGS in Makefile.

For quick information about how to write a Makefile, see this, or this, or this. Or check this last part of this answer.

Then, create the following launch.json:

launch.json

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "make and debug active file",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}/${fileBasenameNoExtension}.out",
      "cwd": "${workspaceFolder}",
      "setupCommands": [
        {
          "description": "Enable pretty-printing for gdb",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        }
      ],
      "preLaunchTask": "${defaultBuildTask}"
    }
  ]
}

Now you can use command palette to try Task: Run Build Task, Task: Run Test Task, Debug: Start Debugging.


Original answer

Please consider Code Runner, as it seems faster (for me) than VSCode's built-in debug procedure for practicing with many small C++ code files. I'll describe how I use that extension to satisfy a similar requirement.

  1. Make sure you've configured your PATH to include clang++ so you can invoke it from the integrated terminal.

    You can also use g++ by substitute clang++ below with g++. I prefer clang++ as it provides stricter checks for C++ beginners like me.

  2. Install the extension.
  3. In your VSCode's settings.json, consider adding the following entries:
    "code-runner.clearPreviousOutput": true,
    "code-runner.preserveFocus": false,
    "code-runner.runInTerminal": true,
    "code-runner.saveFileBeforeRun": true
    
  4. And add the last customization code-runner.executorMap to user/workspace setting that describes which command you would like the extension to send to the terminal when current filename's extension meets the specified ones. For example:
    "code-runner.executorMap": {
        "cpp": "\b\b\b\b\b\b\b\b\b\bclang++ -std=c++17 $fileName -o a.out && ./a.out"
    },
    
    The above setting tells the extension, "When see a .cpp file, send 10 Backspace to terminal (to delete any mistyped characters) and call clang++ -std=c++17 *filename* -o a.out && ./a.out.

    I use this command on my Linux machine, for Windows, try change the filename extension of the output file to .exe and invoke it with .\a.exe or simply a.exe.

  5. Finally, map the Run Code command to your preferred keybinding in VSCode's Keyboard Shortcuts settings. Mine is to bind it to F5 which is originally bound to Debug: Continue.

Happy coding!


Update about make

Read on to learn how to avoid redundant compiling process and speed up case test by utilizing GNU make. I'll do this on Linux and only for C++, since I have not used make on Windows or OS X and C++ is the best for ACM.

  1. Make sure make is installed and in your PATH
  2. Create a file named Makefile (or makefile) under the same directory you invoke make. (Or in another directory and make -f /path/to/Makefile).
  3. Redefine compiler options to whatever you like in the Makefile, e.g.:
    CXX = clang++
    CXXFLAGS = -std=c++17 -g -Weverything -Werror
    
  4. Create auto-target rule for *.out in the Makefile, i.e.:
    %.out: %.cpp
        $(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@
    

    Attention: must use Tab to indent the second line, not Spaces.

  5. Change code-runner.executorMap to :
    "code-runner.executorMap": {
        "cpp": "\b\b\b\b\b\b\b\b\b\bmake $fileNameWithoutExt.out && ./$fileNameWithoutExt.out"
    
  6. (Optional) To ignore *.out for git:
    echo "*.out" >> .gitignore
    
  7. (Optional) To remove *.out in current directory:
    rm *.out
    

Now the Run Code command will invoke make and make will only regenerate .out file when the corresponding .cpp file is newer than the .out file, thus allows us to skip compilation and proceed with testing even smoother.

The CXXFLAGS is for C++ compiler options, CFLAGS is for C compiler options. You can find other language compiler options and their variable name using make -p, Google and GNU make manual#Automatic-Variables.

Upvotes: 4

parth_07
parth_07

Reputation: 1408

To Build/run C++ projects in VS code , you manually need to configure tasks.json file which is in .vscode folder in workspace folder . To open tasks.json , press ctrl + shift + P , and type Configure tasks , and press enter, it will take you to tasks.json

Here i am providing my tasks.json file with some comments to make the file more understandable , It can be used as a reference for configuring tasks.json , i hope it will be useful

After configuring tasks.json , to compile and run your c++ file , press ctrl+shift+B , this is shortcut for running build tools in vscode . Your C++ program will now run on vscode integrated terminal only . If this presents some issues , then change default terminal to cmd(by default it is powershell in windows) and make sure there aren't any spaces in path to your file .

tasks.json

{
    "version": "2.0.0",

    "tasks": [

        {
            "label": "build & run",     //It's name of the task , you can have several tasks 
            "type": "shell",    //type can be either 'shell' or 'process' , more details will be given below
            "command": "g++",   
            "args": [
                "-g",   //gnu debugging flag , only necessary if you want to perform debugging on file  
                "${file}",  //${file} gives full path of the file
                "-o",   
                "${workspaceFolder}\\${fileBasenameNoExtension}",    //output file name
                "&&",   //to join building and running of the file
                "${workspaceFolder}\\${fileBasenameNoExtension}"
            ],
            "group": {
                "kind": "build",    //defines to which group the task belongs
                "isDefault": true
            },
            "presentation": {   
                "echo": false,
                "reveal": "always",
                "focus": true,
                "panel": "shared",
                "clear": false,
                "showReuseMessage": false
            },
            "problemMatcher": "$gcc"
        },

    ]
}

All the properties in the presentation of tasks.json are just used to customize build tasks as per your needs , feel free to change them to what you like best . You can read about presentation properties (and other things) on vscode tasks documentations

Upvotes: 3

Related Questions