VS Code C/C++ 扩展智能感知无法检测环境特定功能

问题描述 投票:0回答:2

当我在 VS Code 上编写 C 代码时,IntelliSense 无法检测到标准库中声明的函数,而项目编译正常。

详情:

flockfile
函数在
void flockfile (FILE *__stream)
中声明为
stdio.h
,但 IntelliSense 错误地对待该函数。

我发现了信息旧的C编译器将未声明的函数视为

int functionname()
。 所以我猜智能感知认为
flockfile
尚未声明,尽管我肯定在使用
stdio.h
的文件顶部包含
flockfile

当我在 VS Code 上打开

stdio.h
时,
fnlockfile
的定义显示为无法访问的代码。

但是,项目可以正确编译,不会出现与

fnlockfile
相关的警告,并且构建的应用程序也可以正常运行。 所以我认为这个问题的根本原因是 IntelliSense 使用的编译器接收到的参数与实际编译器接收到的参数不同。

如何使 IntelliSense 解释代码的效果与实际编译器一样?

我在网上查了相关报道,但没有找到。 在包含

__USE_POSIX199506
之前添加
stdio.h
定义可能会解决该问题,但我在几个文件中使用
stdio.h
,并且我不想每次包含
stdio.h
时都编写该定义。

环境:

主机操作系统:Windows10
来宾操作系统:Ubuntu 22.04.4 LTS (WSL2)
编译器:gcc版本11.4.0(Ubuntu 11.4.0-1ubuntu1~22.04)
编辑器:带有来自 Microsoft 的 C/C++ 扩展的 VS Code(1.87.2) (v1.19.9)

.vscode/c_cpp_properties.json
文件;

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c17",
            "cppStandard": "gnu++17",
            "intelliSenseMode": "linux-gcc-x64",
            "configurationProvider": "ms-vscode.cpptools"
        }
    ],
    "version": 4
}

which gcc
答案
/usr/bin/gcc

我对编译器不太了解,如果这是一个愚蠢的问题,我很抱歉......


编辑(添加小地图可重现示例)

  1. 创建一个新的项目文件夹。

  2. 创建main.c

#include <stdio.h>

int main(void)
{
    flockfile(stderr);
    fprintf(stderr, "hello world\n");
    funlockfile(stderr);
    return 0;
}
  1. 创建

    .vscode
    文件夹,放入上面的
    c_cpp_properties.json

  2. 运行以下命令来构建并运行可执行文件。

$ cc -g -W -Wall -Wno-unused-parameter -iquote . -pthread -iquote platform/linux -c main.c -o main.o
$ cc -g -W -Wall -Wno-unused-parameter -o out.a main.o
$ ./out.a
hello world
  1. 但是,VS Code 中的 IntelliSense 无法正确检测
    flockfile

c visual-studio-code gcc intellisense
2个回答
0
投票

使用 C/C++ 扩展 (cpptools)(以及 VS Code 的许多其他 C/C++ 扩展),智能感知与构建是分开的。请参阅相关官方常见问题解答条目。您要么需要手动配置 VS Code 扩展来提供智能感知,以了解构建的具体情况,要么找到一个同时执行这两种功能的扩展,或者将构建信息集成到 C/C++ 扩展中的扩展,例如 CMake 扩展

在这种特定情况下,您在构建期间传递了

-pthread
,但没有传递给智能感知的 C/C++ 扩展。


0
投票

好的,问题解决了。

我意识到我传递给实际编译器的编译器参数没有被告知智能感知。

所以我将

compilerArgs
参数添加到
c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "compilerArgs": ["-g", "-W", "-Wall", "-Wno-unused-parameter", "-iquote", ".", "-pthread", "-iquote", "platform/linux"], # added this line
            "cStandard": "c17",
            "cppStandard": "gnu++17",
            "intelliSenseMode": "linux-gcc-x64",
            "configurationProvider": "ms-vscode.cpptools"
        }
    ],
    "version": 4
}

然后,智能感知就可以正确检测到

flockfile

感谢所有给我评论的人。

© www.soinside.com 2019 - 2024. All rights reserved.