Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use vscode-clangd with c++11?

How to conf vscode-clangd to use c++11 for lint?

I added both complie_commands.json and complie_flags.txt in workshop.

workshop
|-complie_commands.json
|-complie_flags.txt
|-list.cpp

complie_commands.json

[
   { "directory": "pathto/workshop/",
     "command": "/opt/rh/llvm-toolset-7/root/usr/bin/clang++ -o file *cpp -std=c++11"}
]

compile_flags.txt

-std=c++11

It couldn't recognize auto with error:

'auto' type specifier is a C++11 extension
like image 818
L.SG Avatar asked Oct 19 '25 01:10

L.SG


2 Answers

Set cppStandard in c_cpp_properties.json to c++11. e.g.:

{
  "env": {
    "myDefaultIncludePath": ["${workspaceFolder}", "${workspaceFolder}/include"],
    "myCompilerPath": "/usr/local/bin/gcc-7"
  },
  "configurations": [
    {
      "name": "Linux",
      "intelliSenseMode": "clang-x64",
      "includePath": ["${myDefaultIncludePath}", "/another/path"],
      "macFrameworkPath": ["/System/Library/Frameworks"],
      "defines": ["FOO", "BAR=100"],
      "forcedInclude": ["${workspaceFolder}/include/config.h"],
      "compilerPath": "/usr/bin/clang",
      "cStandard": "c11",
      "cppStandard": "c++11",
      "compileCommands": "/path/to/compile_commands.json",
      "browse": {
        "path": ["${workspaceFolder}"],
        "limitSymbolsToIncludedHeaders": true,
        "databaseFilename": ""
      }
    }
  ],
  "version": 4
}
like image 74
Alan Birtles Avatar answered Oct 21 '25 15:10

Alan Birtles


Note: I've Q&A this kind of question with more details in here

Intro

clangd first check for a compilation database in the directory containing the source file, and then walk up into parent directories until we find one.

compilation database can be:

  1. complie_commands.json: which usually generated by a build system like CMake:
# add the following line to your `CMakeLists.txt` script:
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
  • Every "{...}" in .json file corresponds to a single file(tedious and error-prone to write by hand)
  • See: Generating a JSON compilation database
  1. compile_flags.txt: for simple projects like yours(for all files).

Solution:

As for you, just delete your complie_commands.json keep your compile_flags.txt.

If you really want to try, see format and example and try.


Not Recommended way

You can fix this by adding these config file. (if no compilation database is found)

  1. cmd/ctrl + shift + p: Preferences: Open User Settings (JSON)
  2. Add a single line into your settings.json file:
"clangd.fallbackFlags": [
    "-std=c++11",
    "-std=c99"  // in case you need to write C
  ],
  1. cmd/ctrl + shift + p: clangd: Restart language server

Boom, it worked now!

It will cause .h file error... So not recommended for now.

like image 25
yaoyhu Avatar answered Oct 21 '25 15:10

yaoyhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!