70

I'm looking for an option to gcc that will make it read a source file from the standard input, mainly so I could do something like this to generate an object file from a tool like flex that generates C code (flex's -t option writes the generated C to the standard output):

flex -t lexer.l | gcc -o lexer.o -magic-option-here

because I don't really care about the generated C file.

Does something like this exist, or do I have to use temporary files?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zifre
  • 26,504
  • 11
  • 85
  • 105
  • 1
    The generated C file is good to have around if you ever need to debug that code. – laalto Jun 16 '09 at 20:07
  • 5
    @laalto: That's a good point, but the code that flex generates is not very human readable anyways. – Zifre Jun 16 '09 at 20:11

2 Answers2

86

Yes, but you have to specify the language using the -x option:

# Specify input file as stdin, language as C
flex -t lexer.l | gcc -o lexer.o -xc -
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 3
    I figured it might be - (many other tools use it), but I couldn't find anything about it in the man page... – Zifre Jun 16 '09 at 20:09
  • Note that, here in 2019, this recently broke with gcc 8.2.1. It will now hang while reading from the pipe. – Todd Freed Apr 10 '19 at 03:56
  • @ToddFreed: Assuming that the process generating the source file properly closed its output, then that sounds like it's a bug in GCC. If you have a reproducible test case, I suggest you report that to the GCC maintainers. – Adam Rosenfield Jun 05 '19 at 22:34
  • Excellent! Thanks! – pmor Jan 14 '21 at 23:00
  • Is there a way to still give the file a name, for gcc diagnostics? – creanion May 09 '22 at 15:42
  • (It turns out one can use a preprocessor directive to give it a file name; this can be added on the first line of the input) – creanion May 26 '22 at 14:04
22
flex -t lexer.l | gcc -x c -c -o lexer.o -

Basically you say that the filename is -. Specifying that a filename is - is a somewhat standard convention for saying 'standard input'. You also want the -c flag so you're not doing linking. And when GCC reads from standard input, you have to tell it what language this is with -x . -x c says it's C code.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nos
  • 379
  • 2
  • 6
  • I know what -c is, I just left it out for simplicity (because I have a lot of other options on flex and gcc too). – Zifre Jun 16 '09 at 20:10