how to instruct gcc/clang to output temporary files to a particular directory

clang, clang++, command-line, g++, gcc

Solution

If you use `-save-temps=obj` the temporary files are put in the same directory as the output files, so e.g.

gcc -save-temps=obj -o dir/foo.o foo.c

will create `dir/foo.i`

This is documented in the manual, obviously. All supported options are listed at https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html and that links to https://gcc.gnu.org/onlinedocs/gcc/Developer-Options.html for `-save-temps`.

Problem

While using the `--save-temps` option to save the temporary files, gcc/clang outputs the temporary file in the same directory as the input files. Is there an option to instruct gcc to output the files to some other directory. OR, When not using the `--save-temps` option the temporary files are created in a default directory (i.e. `$TMPDIR` such as `/tmp`) but they are deleted once the object file is created. Is there a way to instruct the compiler to keep those files instead of just deleting them ( i think that the only option is `--save-temps`, which has the problem stated above)

Original source