目的

在ubuntu环境下安装vscode,并编译运行glib程序

运行环境

Linux ubuntu-20 5.15.0-78-generic #85~20.04.1-Ubuntu SMP Mon Jul 17 09:42:39 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

下载

vscode官方下载地址

安装

sudo dpkg -i code_xxxx_xxx.deb

运行

code

安装有用的插件

插件库里面搜索:
chinese 安装中文插件
C/C++ 安装C/C++编译插件
code runner 运行程序的好插件,此插件很好地简化了vscode配置编译环境的步骤,强烈建议安装

举例编译glib小测试程序

使用vscode创建 t1.c 源文件,输入以下测试代码:

#include <glib.h>

int main(void)
{
    g_print("hello, glib\n");
    return 0;
}

编辑器会在 #include <glib.h> 处提示错误:

#include errors detected. Please update your includePath. Squiggles are disabled for this translation unit (/home/yelo/code/test/glib-test/t1.c).C/C++(1696)

原因是找不到glib库文件的包含路径,参考 glib官方文档编译部分
在终端输入以下两条 pkg命令可以查询库文件的包含路径和链接路径:

pkg-config --cflags glib-2.0
pkg-config --libs glib-2.0

将获取的信息添加到 c_cpp_properties.json 文件中:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/glib-2.0",  # 添加1
                "/usr/lib/x86_64-linux-gnu/glib-2.0/include" # 添加2
            ],
            "defines": [],
            "cStandard": "c17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "linux-gcc-x64"
        }
    ],
    "version": 4
}

此时,代码中的红色波浪线就消失了,接下来开始编译、链接环节。
通过安装的 code runner 插件,可以很方便的配置编译,code runner模拟的是比较纯粹的命令行方式来编译,通过设置 executorMap 属性,可以直接将编译链接命令设置好,这里选择 本地配置(workspace),会在源文件目录下生成 settings.json,里面内容如下:

{
    "code-runner.executorMap": {

        "c": "cd $dir && gcc $fileName -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -lglib-2.0 -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "python": "python -u",        
    }
}

定位到源文件界面,右键选择 “Run Code” 即可。
输出内容:

[Running] cd "/home/yelo/code/test/glib-test/" && gcc t1.c -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -lglib-2.0 -o t1 && "/home/yelo/code/test/glib-test/"t1
hello, glib

[Done] exited with code=0 in 0.064 seconds
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐