Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to build task based on the specific file extension?

Specifically, I'd like one keyboard shortcut to build an executable file with the correct compilation command and flags, whether the source file is a .c or a .cpp.

For example, my current tasks file, which compiles .cpp files, is as follows:

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

I noticed that if I change "commands" to "/usr/bin/gcc", it's able to compile .c files.

So what I'm looking to have my tasks file do is:

  1. Extract the extension (.c or .cpp) of the file on which I'm building.
  2. Set a variable that will be given to "command".
  3. Conditionally change that variable to "/usr/bin/gcc" or "/usr/bin/g++", based on the extracted extension.

Is all that possible? Do you have better suggestion to achieve that kind of conditional building?

Thanks!

like image 598
localhost Avatar asked Sep 11 '25 16:09

localhost


1 Answers

You can use the extension Command Variable.

Use the command: extension.commandvariable.file.fileAsKey

The order of the extensions is important.

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "${input:pickCompiler}",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
             ...
             ...
        }
    ],
    "inputs": [
      {
        "id": "pickCompiler",
        "type": "command",
        "command": "extension.commandvariable.file.fileAsKey",
        "args": {
          ".cpp": "/usr/bin/g++",
          ".c": "/usr/bin/gcc"
        }
      }
    ]
}
like image 92
rioV8 Avatar answered Sep 14 '25 06:09

rioV8