How to compile code from stdin? [duplicate]
Asked Answered
L

2

30

The code is quite simple :

test$ cat test.cpp

int main()
{
}

Is there a way to compile the code that is coming from a standard output?

I have tried this :

cat test.cpp | g++ -

and some variations, but none produced executable.


Just some clarifications. I have a program which preprocess a file, and produces another file which I want to compile. I thought about not creating this intermediate file, but to instead produce the object file directly.

Ladanum answered 30/7, 2013 at 13:3 Comment(9)
That’s stdin, not stdout.Merkle
Why are people so interested in compiling from standard input? Is it that hard to generate a file and compile that?Situation
@DavidRodríguez-dribeas My motto is : skip a middle man :)Jolin
Well, you are cat-ing a file... so the middle man is there. If your intention was typing directly into the compiler, then chances are that for anything not absolutely trivial you will make a typo and will have to retype (I know, I have used cat as an editor a few times which is fine if you never mistype)...Situation
Don't do that. If you generate C or C++ code, generate it in some temporary file (perhaps in a tmpfs filesystem like /tmp/), and fork a gcc or a make process to compile it. Read my answer hereBlistery
@DavidRodríguez-dribeas No, ´cat´ is not there. I have something else. A program which parses a header, and creates some code, which needs to be compiled into an obj file.Jolin
@BasileStarynkevitch Any specific reason not to do it? I do not really care for the speed of the compilation.Jolin
Read my answer here which gives a lot of reasons for not doing it.Blistery
For my part, I just needed to check the presence of a header. So, not creating a file is simpler than creating it then remove it. My solution: ``` is_header_present() { header_name=$1 gcc -o /dev/null $CFLAGS -x c++ - <<EOTEST #include "$header_name" int main() { return 0; } EOTEST return $? } ```Terris
A
49

The compiler would have probably told you:

-E or -x required when input is from standard input

Try

cat test.cpp | g++ -x c++ -
Afterdamp answered 30/7, 2013 at 13:8 Comment(4)
Yes, it told me, but it didn't tell to put c++ after. After adding c++ it worksJolin
@Ladanum In these cases, you are supposed to read the documentation of the particular compiler flag you will be using. -x is documented to require the language as its argument.Gipsy
@H2CO3 The error message is not helpful at all (if you do not provide the language). Also, the ´-´ has to be at the end. Try to find such details in g++ documentationJolin
@Afterdamp Please explain the need for that last -; it appears it can be omitted, yet is somehow necessary?Phillie
T
2

Did you try this ?

$ cat tst.cpp | g++ -x c++ -

I have just tried it under Cygwin and had no problem.

Tripartition answered 30/7, 2013 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.