VSCode:设置 C/C++ 预处理器宏进行静态分析

Sma*_*ft2 3 c++ c-preprocessor preprocessor-directive visual-studio-code

我正在开发一个库,它允许用户设置关键类型别名,或者通过预处理器指令来完成。根据设计,此类型别名(或指令)在库中未声明。因此,在开发代码时,我会收到这种未声明类型的烦人的错误消息和波形曲线。如果我在某处为其声明一个临时类型,则可以避免这种情况。但是,我不喜欢在使用代码时声明它,然后在发布代码时将其删除的想法。它也容易出现错误,因为我很容易忘记删除它。

我的问题是: 我可以为 VS Code 的静态分析(IntelliSense?C/C++ 扩展)定义预处理器指令吗?

这会让我考虑像定义良好的类型别名会产生什么一样的分析。并避免烦人的错误消息/曲线。


最小可重现示例:

在线编译示例

tCore.hpp

#pragma once

#include <string>

// User is responsible of declaring the tCore type

// tCore interface methods 
template<typename TCore>
std::string printImpl();
Run Code Online (Sandbox Code Playgroud)

tPrint.hpp

#pragma once

#include <iostream>

class tPrint {
  public:
    tPrint() = default;
      
    void print() const {
        std::cout << printImpl<tCore>() << std::endl; // <-- Static analysis error here!
    }
};
Run Code Online (Sandbox Code Playgroud)

tFoo.hpp - tCore 候选者

#pragma once

#include <string>
#include "tCore.hpp"

struct tFoo {};

template<>
std::string printImpl<tFoo>() {
    return "tFoo";
}
Run Code Online (Sandbox Code Playgroud)

主程序

#include <tFoo.hpp>

using tCore = tFoo;

int main() {
    tPrint p{};
    p.print();  // -> "tFoo"
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sma*_*ft2 7

我发现是IntelliSense通过C/C++ Extension导致了错误。

我还找到了将编译器参数添加到IntelliSense 的选项,这正是我正在寻找的。

通过用户界面:

按 F1 -> > C/C++: Edit Configurations (UI)-> 向下滚动至Defines

或者通过 JSON :

c_cpp_properties.jsondefines配置有一个保存任何编译器参数的字段。