是否可以基于特定的文件扩展名构建任务?

3

具体来说,我希望有一个键盘快捷方式,可以使用正确的编译命令和标志构建可执行文件,无论源文件是.c还是.cpp

例如,我的当前任务文件编译.cpp文件如下:

{
    "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."
        }
    ]
}

我注意到如果我将"commands"更改为"/usr/bin/gcc",就能够编译.c文件。

所以我想要我的任务文件做到以下几点:
  1. 提取正在构建的文件的扩展名 (.c.cpp)。
  2. 设置一个将被赋予"command"的变量。
  3. 有条件地将该变量更改为"/usr/bin/gcc""/usr/bin/g++",根据提取的扩展名而定。
这都是可能的吗?您对实现这种条件构建有更好的建议吗?
谢谢!

你可以在按键绑定的where子句中添加languageid==cpp,并将命名任务作为绑定的命令运行。 - rioV8
1个回答

2
你可以使用扩展程序Command Variable
使用命令:extension.commandvariable.file.fileAsKey 扩展程序的顺序很重要。
{
    "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"
        }
      }
    ]
}

谢谢!看起来让我更接近了一些(在将pickCompiler更改为PickCompiler后),但是现在在尝试构建时,我收到了“找不到命令'extension.commandvariable.file.fileAsKey'”的消息。 - localhost
1
@Benjamin,你看到回答的第一行了吗?我会修复这个错别字。 - rioV8
哦,你说得对!我对这一切都很陌生。安装了扩展后,我现在遇到了以下编译错误:“${input:PickCompiler} -g /..path../name.cpp -o /..path../name /bin/sh: 1: Bad substitution”。我无论是在 .c 还是 .cpp 文件中都遇到了这个问题。 - localhost
@Benjamin,请问你当前的 tasks.json 内容是什么?请编辑你的问题。 - rioV8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接