Setting a Default C++ Standard for clangd
clangd needs to know which language standard a file is written in. Inside a real project it reads the answer from compile_commands.json. For everything else, such as a scratch file, a snippet from a blog post or a header opened on its own, it falls back to the compiler’s default. Clang 15 and earlier defaulted to gnu++14, so std::string_view showed up as an error. Since Clang 16 the default is gnu++17, which still rules out concepts, ranges, std::format and everything else after C++17.
There are two ways to change that, and they behave differently in one important respect.
The fallback flags (recommended)#
clangd accepts fallback flags: extra arguments used only when a file has no entry in a compilation database. In VS Code they are a setting of the clangd extension:
"clangd.fallbackFlags": ["-std=c++23"]
Other editors pass the same list as the fallbackFlags initialization option of the language server.
Files that belong to a project are unaffected and keep the standard their build uses. The catch is that the flags apply to every loose file, C files included, and clangd will complain that -std=c++23 is not allowed with C. If you rarely open stray C files, this is the setting to use.
The user config file#
clangd also reads a user-level configuration file:
| Platform | Path |
|---|---|
| Linux | ~/.config/clangd/config.yaml |
| macOS | ~/Library/Preferences/clangd/config.yaml |
| Windows | %LocalAppData%\clangd\config.yaml |
This file can be conditioned on the path, so it can keep C files out:
If:
PathExclude: [.*\.c, .*\.h]
CompileFlags:
Add: [-std=c++23]
Excluding .h keeps C headers clean, at a price: C++ headers that use the .h extension fall back to the compiler default. If your C++ code uses .h headers, exclude only .*\.c.
Be aware of what Add does, though. It appends the flag to every compile command, including those that come from compile_commands.json, and when a command contains two -std flags the last one wins. A project that builds as C++17 will therefore be analysed as C++23, and clangd may accept code that your compiler rejects. A project-level .clangd file cannot undo this by adding its own -std, because the user configuration is applied after it. The safe use of this file is a rule scoped to the directories where you keep loose code:
If:
PathMatch: /home/me/scratch/.*\.(cpp|cc|hpp)
CompileFlags:
Add: [-std=c++23]
The configuration reference documents the full format.
Checking the result#
clangd --check=path/to/file.cpp prints the compile command it settled on, either “Compile command from CDB is” or “Generic fallback command is”, followed by the arguments. Look for the -std flag at the end of the line. Note that --check does not see editor settings, so it reflects the config file but not clangd.fallbackFlags.
Every behaviour described here was checked with clangd 23.