Search code examples
c++visual-studio-codegcccompiler-optimizationmingw-w64

C++ compiler optimisations (MSYS2 MinGW-64 bit GCC compiler used with VSCode)


I'm trying to apply the different optimisation levels (-O0, -O1, -O2, -O3 and so on) to the compilation and execution of a .cpp file.

However, I can't figure out the exact syntax I need to use and where to write the instructions (i.e. in which terminal, the VSCode terminal or the MinGW terminal)?

Any help would be much appreciated.

tasks.json:

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

Solution

  • In this field:

            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
    

    add the optimization option:

            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "-O2"
            ],
    

    Consider that you have two tasks (I am not sure why you have the second one) and you need to set it in the correct task. If I were you I would remove the unused one and instead create a task for debug and release build: Release build in Visual Studio Code

    Be careful that this is about c# and cannot be copy pasted!