God bless
God bless

Reputation: 123

Run C++ in Visual Studio Code without opening it with `code .` from CMD

I set up VSCode to compile C++, but in order to be able to run it, I first have to open CMD, navigate to the location of the .cpp file I want to open and then run code . (This opens VSCode and then I can compile the file with Ctrl+Shift+B.) This is tedious and it would be wonderful if I had a script that enabled me to run C++ without having to do the above procedure every time.

Thank you for your help. :)

EDIT

This is my tasks.json file:

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++.exe build active file",
            "command": "C:\\msys64\\mingw64\\bin\\g++.exe",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\\msys64\\mingw64\\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "compiler: C:\\msys64\\mingw64\\bin\\g++.exe"
        }
    ]
}

Upvotes: 0

Views: 2129

Answers (1)

effect
effect

Reputation: 1455

For your particular case with a single .cpp file and g++ installed, you should be able to compile from the command line using a command similar to below:

g++ -fdiagnostics-color=always -g <.cpp file name> -o <output binary name>

Make sure to replace <.cpp file name> with your actual filename and <output binary name> with whatever you want to name your executable.

It appears you are first starting to learn how to develop in C++. This solution above should work for now.

When you start to write bigger programs and decide to split your source code into multiple files, you will eventually want to learn how to use a build system that can help automate the compilation of multiple source files. A popular build system is GNU Make, this would probably be a good tool to learn. You can write makefiles which instruct how to build the code, and then VSCode can be configured to use make to read the makefiles and build the code.

Upvotes: 1

Related Questions