-std flag not always present in compile_commands.json
I sometime face an issue when building a CMake project with GCC, setting CMAKE_EXPORT_COMPILE_COMMANDS
and using clangd with the resulting compile_commands.json.
Sometimes, even though a target has the cxx_std_xy
compile feature enabled, the standard version flag is not emitted by CMake when invoking the compiler to build it. My guess is that it matches the compiler's default mode and so CMake skips it.
The issue is that this same command line is used to generate the compile_commands.json file that is parsed by a different compiler (here clang) with a possible different default standard version. This leads to errors showing up in IDEs even though the build is fine.
IMO it would be best to always emit the standard flag when outputting the compilation database but I guess it might requires to always emit it in compiler invocations as well. I don't see a big problem with that, and I even think it would be better to always know which standard is used when looking at the compiler invocation, but I'm not familiar with CMake's internals so I might be missing something.
I made a small project on compiler explorer to show that standard version flags are not always emitted: https://godbolt.org/z/5srjcG7f7
When making this demo, I even realized that setting target_compile_features(hello_98 PUBLIC cxx_std_98)
doesn't generate an -std flag on the two GCC versions tested. This allows to write code valid only in later standard versions without realizing it...