Redirecting gcc diagnostics into a file

During my CI build i want to use -fdiagnostics-format=json to generate a nice build report.
How can i redirect the output of every compiler call into a file?
On a command line i would write

gcc -c -fdiagnostics-format=json foo.c |& tee > foo.c.log

1 Like

You’d need to probably edit the compiler command template to have an additional set of flags. I don’t think CMake supports shell logic like |& tee > foo.log in general however. I would recommend using CMAKE_<LANG>_COMPILER_LAUNCHER to wrap this up in a tool that can launch the compiler in an explicit shell that handles the redirection.

Thanks. Yes i think you are right.

I spend the afternoon with writing a shell command wrapper that replaces “gcc” and inject it via CC and CXX environment variables. Works very well now.

I think the feature to specify a special error file is something that must be implemented by the compiler developers and not in the build system. So i will post on the gcc/clang forum. Its time in 2021 to stop parsing output for structured data.

Do you plan to publish your script?

#!/usr/bin/bash

# We need at least three arguments with the last "-c path_to_src.cpp"
if [ $# -le 2 ]
then
    gcc "$@" ; exit $?
fi


# Last argument must have the right file extension,  ".c"
last=${@: -1}
filename=$(basename -- "$last")
extension="${filename##*.}"
filename="${filename%.*}"
if [ "$extension" != "c" ]
then
    gcc "$@" ; exit $?
fi


# Find out we are compiling one of our own source files
case "$last" in
  */infosqueezer/src/*)
	     echo " " > /dev/null
    ;;
  *)
      gcc "$@" ; exit $?
    ;;
esac


# check second last argument is a -c
switch=${@: -2:1}
case "$switch" in
  -c)
	echo " " > /dev/null
    ;;
  *)
      gcc "$@" ; exit $?
    ;;
esac


out_path=${INFOSQUEEZER_BUILD_STATUS_PATH}/${filename}.${extension}.olog
err_path=${INFOSQUEEZER_BUILD_STATUS_PATH}/${filename}.${extension}.elog

gcc "$@" > >(tee ${out_path}) 2> >(tee ${err_path} >&2)

I will extend and program it in c now when i now it works and i tasted the blood of good build status information Bash is just to ugly for me and i also want to catch linking steps now and a lot of other things like timing of the individual calls.