【问题标题】:Visual Studio Code with Bash Terminal (WSL) in C++ builds only .out files - not .exeC++ 中带有 Bash 终端 (WSL) 的 Visual Studio Code 仅构建 .out 文件 - 而不是 .exe
【发布时间】:2018-05-05 00:11:33
【问题描述】:

我在带有 Linux 子系统的 Windows 10 上使用 Visual Studio Code。 (Ubuntu)

我创建了一个小的 c++ 文件,当我使用 bash 终端构建它时 - 只创建了一个 .out 文件。这很好,但我也想调试它,在这种情况下 - 我只能打开 .exe 文件。

当我从 bash 切换到 powershell - 构建扩展是一个 .exe

tasks.json

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "echo",
      "type": "shell",
      "command": "g++",
      "args": [
        "-g", "main.cpp"
      ],
      "group": { "kind": "build", "isDefault": true }
    }
  ]
}

launch.json for debugging 

{
      "name": "(gdb) Launch",
      "type": "cppdbg",
      "request": "launch",
      "program": "${workspaceFolder}/a.exe", // .out doesn't work here
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": true,
      "MIMode": "gdb",
      "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe",
      "preLaunchTask": "echo",
      "setupCommands": [
        {
          "description": "Enable pretty-printing for gdb",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        }
      ]
    }

main.cpp

#include <iostream>

int main() {
  std::cout << "hello a" << std::endl;
}

我真的不知道该怎么做 - 因为我无法调试 .out 文件,我想自己选择构建扩展。

【问题讨论】:

  • 您正在从 linux 机器(WSL 终端大致是 linux 虚拟机)调用 g++,因此它会生成与 linux 兼容的二进制文件。如果您希望它为不同的机器(例如您的 windows 机器)生成二进制文件,则必须进行交叉编译(我自己从未做过,但编译器倾向于支持它)
  • 谢谢@Justin - 感谢您的交叉编译提示,找到了解决方案。
  • g++ -g main.cpp -o main.exe 对吗?

标签: c++ bash visual-studio-code windows-subsystem-for-linux


【解决方案1】:

找到解决方案:

sudo apt-get install mingw-w64

然后在tasks.json中

"command": "i686-w64-mingw32-g++"

编译一个 32 位 exe - 但是带有 x86_64-w64-mingw32-g++ 的 64 位版本不知何故不起作用。创建一个无效的 exe。

【讨论】:

    【解决方案2】:

    为了跨平台运行/调试,您必须使用交叉编译器,例如 MinGW。您可以在 Windows、Linux(或 WSL)中安装 MinGW-w64

    VScode-tools 和 MinGW 的 gdb.exe 可以调试 *.out*.exe 文件(已测试)。

    要编译 64 位版本,您需要在编译时包含一些用于 C/C++ 的静态依赖库,即 libgcclibstdc++。所以task.json中的commandargs应该是:

    "command": "x86_64-w64-mingw32-g++",
    "args": [
               "-g",                  //Need for debug and compatibility
               "-static-libgcc",      //flag for the libgcc
               "-static-libstdc++",   //flag for the libgc++
               "helloworld.cpp",      //C++ source code
               "-o",                  //flag for output
               "a2.out"               //Output filename and extension (can be .exe) 
                ],
    

    您可以了解更多关于 C/C++ 标准库依赖here

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      相关资源
      最近更新 更多