【VSCode】C语言动态库调试

因为项目的需要,需要在VSCode中调试C语言写的动态库

  1. 因为是在Linux环境下的,所有先使用Docker创建一个容器用于测试

    1
    docker run -itd --name c_lib_dbg_test ubuntu:20.04
  2. 然后在VSCode中使用远程资源管理器连接到容器

  3. 使用终端工具在容器中安装相关环境

    1
    apt update -y && apt install -y gcc gdb vim
  4. 创建项目文件夹

    1
    mkdir -p ~/test
  5. 用VSCode打开该文件夹

  6. 添加 test_so.c 文件,内容如下

    1
    2
    3
    4
    5
    6
    int test_so(int a, int b) 
    {
    a = a * b;
    a = a + 1;
    return (a);
    }
  7. 试着用命令编译一下并使用工具查看一下符号

    1
    2
    gcc test_so.c -fPIC -shared -g -o test_so.so
    nm -D test_so.so
  8. 添加 main.c 文件,内容如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    #include <stdio.h>
    #include <stdlib.h>
    #include <dlfcn.h>

    typedef int(*test_so_func)(int a, int b);

    int main(void)
    {
    void *so_handle = dlopen("./test_so.so", RTLD_LAZY);
    if (so_handle == NULL) {
    fprintf(stderr, "%s\n", dlerror());
    exit(-1);
    }
    test_so_func func = dlsym(so_handle, "test_so");
    if (func == NULL) {
    fprintf(stderr, "%s\n", dlerror());
    exit(-2);
    }
    printf("func(5, 6) = %d\r\n", func(5, 6));
    dlclose(so_handle);
    return 0;
    }
  9. 再编译一下

    1
    gcc main.c -rdynamic -ldl -o main -g
  10. 运行一下

    1
    2
    root@e7ad9bf88594:~/test# ./main
    func(5, 6) = 31

    可以看到运行结果是31,刚好对应上 5 * 6 + 1,说明调用成功

  11. 在VSCode接着安装以下插件(包)

    • C/C++ Extension Pack
  12. 然后点击左侧的运行和调试按钮,然后点击按钮右侧的创建 launch.json 文件

  13. 然后选择 C++ (GDB/LLDB)

    文件内容如下,就修改了 programcwd 参数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    {
    // 使用 IntelliSense 了解相关属性。
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
    {
    "name": "(gdb) 启动",
    "type": "cppdbg",
    "request": "launch",
    "program": "${workspaceFolder}/main",
    "args": [],
    "stopAtEntry": false,
    "cwd": "${workspaceFolder}",
    "environment": [],
    "externalConsole": false,
    "MIMode": "gdb",
    "setupCommands": [
    {
    "description": "为 gdb 启用整齐打印",
    "text": "-enable-pretty-printing",
    "ignoreFailures": true
    }
    ]
    }
    ]
    }
  14. 打开 test_so.c,在 a = a + 1; 行下个断点

  15. 点击左侧调试中的 运行 按钮,可以看到程序直接运行到了 a = a + 1; 语句

小结

调试动态库是必须要有一个调用他的可执行程序才能调试的。

【VSCode】C语言动态库调试

https://biteax.com/29df39f9.html

作者

石志超

发布于

2021-12-16

更新于

2023-09-27

许可协议