Is there a preprocessor directive to read source from standard input during compilation? [duplicate]
Pos开发者_StackOverflow社区sible Duplicate:
How to write program during compiling?
I found this problem on a site full of interview questions, and was stumped by it. Is there some preprocessor directive that allows one to read from standard input during compilation?
Write a small C program, which while compiling takes another program from input terminal, and on running gives the result for the second program. (NOTE: The key is, think UNIX). Suppose, the program is 1.c Then, while compiling
$ cc -o 1 1.c
int main() { printf("Hello World\n"); } ^D
$ ./1
Hello World
EDIT It turns out this question is an exact duplicate. How to write program during compiling?
#include "/dev/stdin"
is the trick.
A silly interview question at best.
In the spirit of one-upmanship, I tried to make a more platform/environment-independent version. However, I got stuck here... so this is my question, what can I replace '???' with?
#ifdef _WIN32
#include ???
#else
#include "/dev/stdin"
#endif
EDIT: Thanks to ohmantics I can now get the job with:
#ifdef _WIN32
#include "CON"
#else
#include "/dev/stdin"
#endif
You need to tell the compiler to take its source code input from the standard input, and compile that. There is very probably a command line argument for that.
This way, you can pipe the output of another program into your compiler.
EDIT As usual, Stack Overflow already had an answer for this.
echo "int main() { return 0; }" | gcc -x c -
EDIT Missed the while compiling statement. The piping trick still works otherwise though, so I'll leave it there.
精彩评论