如何使用vscode在C中调试'extern'

时间:2020-04-01 11:08:40

标签: c visual-studio-code vscode-code-runner

我不熟悉c编译器,我知道如何在终端中使用gcc或g ++

我有

main.c

#include <stdio.h>

int count;
extern void write_extern();

int main()
{
   count = 5;
   write_extern();
}

support.c

#include <stdio.h>

extern int count;

void write_extern(void)
{
   printf("count is %d\n", count);
}

gcc main.c support.c

和输出文件a.out正常工作

但是如果我使用vscode或代码运行程序插件进行调试 错误显示

/“主要 架构x86_64的未定义符号: “ _write_extern”,引用自: _main在main-217186.o中 ld:找不到架构x86_64的符号 铛:错误:链接器命令失败,退出代码为1(使用-v查看调用)

我的launch.json和task.json看起来像这样:

 "configurations": [
        {
            "name": "clang build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "lldb",
            "preLaunchTask": "clang build active file"
        }
    ]
{
    "tasks": [
        {
            "type": "shell",
            "label": "clang build active file",
            "command": "/usr/bin/clang",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "/usr/bin"
            }
        }
    ],
    "version": "2.0.0"
}

如何配置?

1 个答案:

答案 0 :(得分:1)

默认情况下,该任务仅编译当前打开的文件,因此您需要更改启动前任务以编译所需的所有内容。您可以为此创建一个自定义任务,如下所示:

{
"tasks": [
    {
        "type": "shell",
        "label": "clang build active file",
        "command": "/usr/bin/clang",
        "args": [
            "-g",
            "${file}",
            "-o",
            "${fileDirname}/${fileBasenameNoExtension}"
        ],
        "options": {
            "cwd": "/usr/bin"
        }
    },
    {
        "type": "shell",
        "label": "clang build custom",
        "command": "/usr/bin/clang",
        "args": [
            "-g",
            "${fileDirname}/main.c",
            "${fileDirname}/support.c",
            "-o",
            "${fileDirname}/main"
        ],
        "options": {
            "cwd": "/usr/bin"
        },
        "problemMatcher": [
            "$gcc"
        ],
        "group": "build"
    }
],
"version": "2.0.0"
}

然后更新您的launch.json以使用新任务:

 "configurations": [
    {
        "name": "clang build and debug custom project",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}/${fileBasenameNoExtension}",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": false,
        "MIMode": "lldb",
        "preLaunchTask": "clang build custom"
    }
]