Search code examples
c++ccompiler-warningsclangd

How to use compile_flags.txt for C++ programming and suppress C++ related issues for development in C?


Recently I wanted to use a compile_flags.txt-file to allow development in C++20. Clangd shows annoying warnings when using structured-bindings and C++-related features and so I created this file. My compile_flags.txt-file looks like this:

-std=c++20

When I want to edit a C-file however, clangd complains for the basic include directive: #include <stdio.h>:

clang[drv_argument_not_allowed_with]: Invalid argument '-std=c++20' not allowed with 'C'.

Naturally, I removed the compile_flags.txt-file and it works fine. How can I achieve writing C++20-code and C-code at the same time without manually removing the file every time I decide to switch between the two? Thanks for any help in advance :^)


Solution

  • If you don't want to use a compile_commands.json file, another mechanism for providing flags to clangd that is more flexible than compile_flags.txt is a clangd config file.

    Clangd config files can specify compiler flags to be added, and you can limit your configuration to only files whose path matches a certain pattern (for example, files with a certain extension). This allows specifying different configuration for different languages based on the file extension.

    Here is an example of a config file that specifies that the flag -std=c++20 should be added for .cpp files, and the flag -std=c17 should be added for .c files:

    If:
      PathMatch: .*\.cpp
    
    CompileFlags:
      Add: [-std=c++20]
    
    ---
    
    If:
      PathMatch: .*\.c
    
    CompileFlags:
      Add: [-std=c17]
    

    This would go into a file named .clangd in your project's root directory.