blog/posts/clang-get-started.md
2024-12-16 17:27:47 +00:00

4.0 KiB
Raw Permalink Blame History

Debian for WSL 配置C语言开发环境


::: tip 写在前面的话 本文章已经默认你会使用WSLVSCode且你的WSL为Debian发行版。 :::

在Debian中安装ClangGDB

apt-get install clang gdb

执行上述操作后,通过 clang -vgdb -v,如果能看到输出正确的版本信息,则表示安装完成。

::: details 版本信息示例 :::code-group

Debian clang version 14.0.6
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Candidate multilib: .;@m64
Selected multilib: .;@m64
GNU gdb (Debian 13.1-3) 13.1
Copyright (C) 2023 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

:::

Clang包,作为C语言的编译和解释器,用来编译C文件代码。GDB用来在vscode中调试C文件。 :::tip 提示 在Mac上,安装Clang,默认会使用lldb进行调试。但我尝试在Debian上,Clang可以正常的使用,但是lldb不能使用,即使安装了lldb包,在vscode中配置了lldb为默认调试,也不能正常使用。所以,我选择使用gdb来替代lldb,在Debian上可以正常配合vscode使用了。 :::

在vscode中配置C

安装C/C++扩展

C++扩展

新建 c_cpp_properties.json 调用clang编译器

在当前项目下,新建 .vscode文件夹,并在此目录中,新建 c_cpp_properties.json文件: 并添加以下内容:

{
  "configurations": [
    {
      "name": "Linux",
      "includePath": [
          "${workspaceFolder}/**"
      ],
      "defines": [],
      "compilerPath": "/usr/bin/clang",
      "cStandard": "c23",
      "cppStandard": "c++23",
      "intelliSenseMode": "linux-clang-x64"
    }
  ],
  "version": 4
}

此文件用来配置C/C++扩展,其中设置了编译器为 /usr/bin/clang 这样当前项目就可以通过C/C++扩展来使用当前系统安装的clang编译器了。

新建 tasks.json,用于调试前进行项目编译

{
  "tasks": [
    {
      "type": "cppbuild",
      "label": "C/C++: clang++ build active file",
      "command": "/usr/bin/clang",
      "args": [
        "-fcolor-diagnostics",
        "-fansi-escape-codes",
        "-g",
        "${file}",
        "-o",
        "${fileDirname}/${fileBasenameNoExtension}"
      ],
      "options": {
        "cwd": "${fileDirname}"
      },
      "problemMatcher": [
        "$gcc"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "detail": "Task generated by Debugger."
    }
  ],
  "version": "2.0.0"
}

新建 launch.json ,配置项目自动编译和调试任务

{
  // 使用 IntelliSense 了解相关属性。 
  // 悬停以查看现有属性的描述。
  // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(lldb) 启动",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}/${fileBasenameNoExtension}",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${fileDirname}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "gdb",
      "preLaunchTask": "C/C++: clang++ build active file",
      "miDebuggerPath": "/usr/bin/gdb"
    }
  ],
}

新建 main.c 文件,测试系统是否正常

#include <stdio.h>

int main () {
  printf("hello world, %s \n", "mike");
  return 1;
}

按键盘上的F5启用调试,则vscode应该会自动运行调试,执行编译和运行。