问题描述
我正在开发一个库,它允许用户设置一个关键的类型别名,或者通过预处理器指令来完成。 根据设计,此类型别名(或指令)在库中未声明。因此,在开发我的代码时,我会收到令人讨厌的错误消息和这种未声明类型的波浪线。如果我在某处为其声明一个临时类型,则可以避免这种情况。但是,我不喜欢在使用代码时声明它然后在发布时将其删除的想法。它也很容易出错,因为我很容易忘记删除它。
我的问题是: 我可以为 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();
tPrint.hpp
#pragma once
#include <iostream>
class tPrint {
public:
tPrint() = default;
void print() const {
std::cout << printImpl<tCore>() << std::endl; // <-- Static analysis error here!
}
};
tFoo.hpp - tCore 候选
#pragma once
#include <string>
#include "tCore.hpp"
struct tFoo {};
template<>
std::string printImpl<tFoo>() {
return "tFoo";
}
main.cpp
#include <tFoo.hpp>
using tCore = tFoo;
int main() {
tPrint p{};
p.print(); // -> "tFoo"
return 0;
}
解决方法
我发现是 IntelliSense 通过 C/C++ 扩展导致错误。
我还找到了向 IntelliSense 添加编译器参数的选项,这正是我想要的。
通过用户界面:
按
F1 -> > C/C++: Edit Configurations (UI)
-> 向下滚动到 Defines
或者通过 JSON :
c_cpp_properties.json
配置有一个字段 defines
,其中包含任何编译器参数。