让 clangd 知道编译器给出的宏

Make clangd aware of macros given from the compiler

我有两个从同一来源(一个客户端和一个服务器)构建的可执行文件,它们是使用服务器的编译选项 -D CLIENT=0 -D SERVER=1 和客户端的编译选项 -D CLIENT=1 -D SERVER=0 构建的。如果我做类似

的事情
if (CLIENT) {
// Client specific code
}

clangd 抱怨没有定义 CLIENT。有没有办法让 clangd 知道这些宏? (代码编译得很好,错误来自 clangd,而不是编译器)

Is there a way to make clangd aware of those macros?

来自getting started with clangd

Project setup

To understand source code in your project, clangd needs to know the build flags. (This is just a fact of life in C++, source files are not self-contained.)

By default, clangd will assume that source code is built as clang some_file.cc, and you’ll probably get spurious errors about missing #included files, etc. There are a couple of ways to fix this.

compile_commands.json

compile_commands.json file provides compile commands for all source files in the project. This file is usually generated by the build system, or tools integrated with the build system. Clangd will look for this file in the parent directories of the files you edit. Other tools can also generate this file. See the compile_commands.json specification.

compile_commands.json 通常使用 CMake 构建系统生成,但更多构建系统尝试生成它。

我建议将您的项目转移到 CMake,在此过程中您将学习这个工具,这肯定会帮助您进行进一步的 C-ish 开发。

compile_flags.txt

If all files in a project use the same build flags, you can put those flags, one flag per line, in compile_flags.txt in your source root.

Clangd will assume the compile command is clang $FLAGS some_file.cc.

Creating this file by hand is a reasonable place to start if your project is quite simple.

如果不移动到 cmake,创建一个 compile_flags.txt 文件,内容如下,clangd 应该选择这个文件:

-DCLIENT=1
-DSERVER=1