如何设置Visual Studio Code以在Linux上调试C程序?

时间:2019-08-31 14:06:37

标签: ubuntu gcc visual-studio-code gdb

我正在尝试在Visual Studio Code中调试C程序。
在我的目录中,我有2个文件test.cMakefile以及.vscode文件夹,其中包含launchtasks json文件。
我在过去三个小时内尝试配置这些文件,以搜索各种论坛和博客,但似乎无济于事。

我能够使用这两个json文件进行编译和运行。
程序运行并正确显示输出,但不会在断点处停止,在程序执行期间,我无法添加断点,并且已经添加的断点会被以下消息禁用。

  

包含此断点的模块尚未加载,或者无法获取断点地址。

似乎VSCode在调试阶段无法找到我的test.c文件,即使该文件位于同一目录中也是如此。如果有人可以向我展示正确的方法,那就太好了。
在这里,我要在文件夹中附加文件内容。
launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "gcc build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/test",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "tasks",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}

tasks.json

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "tasks",
            "type": "shell",
            "command": "make",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Makefile

all:
    gcc test.c -o ./test

test.c

#include<stdlib.h>
#include<stdio.h>

int main(){
    printf("Mandar\n");
    printf("Sadye\n");
    return 0;
}

谢谢。

1 个答案:

答案 0 :(得分:1)

您的配置是正确的,除了一件小事情:您忘记将-g标志传递给gcc。因此,test程序中没有调试信息,因此gdb不知道源代码和编译程序之间的关系。

此外,Makefile中的目标应指定它们所依赖的文件。您的all目标与test.c没有依赖关系,因此更改源代码不会导致重新编译。

这里是固定的Makefile

all: test

test: test.c
        gcc -g test.c -o ./test

有了此修复程序,我就能使用VSCode 1.36.1在Linux上编译和调试该程序。