【问题标题】:Is it possible to build task based on the specific file extension?是否可以根据特定的文件扩展名构建任务?
【发布时间】:2021-06-01 02:32:02
【问题描述】:

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

比如我现在编译.cpp文件的tasks文件如下:

{
    "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,并将命名任务作为绑定的命令运行

标签: c++ c visual-studio-code vscode-tasks


【解决方案1】:

您可以使用扩展名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 之后),但我现在在尝试构建时收到“command 'extension.commandvariable.file.fileAsKey' not found”消息。
  • @Benjamin 你读过答案的第一行吗?我会改正错字
  • 哦,你说得对!我对这一切都很陌生。安装扩展后,我现在收到以下编译错误:“${input:PickCompiler} -g /..path../name.cpp -o /..path../name /bin/sh: 1:糟糕的替代品”。我为 .c 和 .cpp 都得到了这个
  • @Benjamin 您当前的tasks.json 内容是什么,编辑您的问题
猜你喜欢
  • 2017-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
相关资源
最近更新 更多