[CMake] Saving clang output to file when cmake is used with CLion

Dan Liew dan at su-root.co.uk
Thu Apr 13 05:45:30 EDT 2017


Hi,

On 13 April 2017 at 01:35, mike lojkovic <mikelojkovic at gmail.com> wrote:
> I have a script I'm using to figure out which headers should be in my
> precompiled header. It requires the clang -H flag passed to work. I'm
> able to get the output on the console without issue, but can't figure
> out how to just pass clang's output to a file for my script to
> analyze. redirecting the console output to a file with ">" won't work
> since I'm compiling from CLion. Is there a way to do this from within
> a CMakeLists.txt?  I'm thinking something like tee would work, but
> can't find a variable to chain to tee.

I have two ideas for this

1. Write a wrapper script for clang and tell CMake to use that as the
compiler. Something like this would do it

```
#!/bin/bash
: ${STDOUT_DEST?"STDOUT_DEST is not set"}
: ${STDERR_DEST?"STDERR_DEST is not set"}
CLANG_BIN="$(which clang)"
{ ${CLANG_BIN} "$@" 2>&1 1>&3 3>&- | tee -i ${STDERR_DEST}; } 3>&1
1>&2 | tee -i ${STDOUT_DEST}
```

this wrapper script logs the standard output and standard error to
separate files (overwriting existing files). The file names are set by
environment variables. You'll probably need to modify this script to
suit your needs.

then configure cmake to use this as the compiler

```
CC=/path/to/clang_wrapper cmake /path/to/source_dir
```

If you have C++ code you'll need to write a similar wrapper for `clang++`.

2.  Use the compilation database [1] which will record all the clang
invocations and then write a script to read the JSON file
and re-run the commands with the `-H` flag added and capture the
output and do whatever you need to do with it.

[1] https://clang.llvm.org/docs/JSONCompilationDatabase.html


HTH,
Dan.


More information about the CMake mailing list