9

Really off the wall question here, but is there a way to compile a string of C code in GCC without any medium to hold that string (eg. a source file)?

Something along the lines of:

$ gcc "#include <stdio.h> int main( void ){ printf('hello world'); return 0;}" -o test

Feels really dirty, but it would be really nice if there was some simple way to do that type of thing.

2

2 Answers 2

12

If you use - as the input file in the command line, gcc reads from standard input. Since there is no file name extension gcc could use to find out the language that should be compiled, it has to be specified with the -x flag:

$ gcc -x c -o tst - <<EOF
> #include <stdio.h>
> int main(void) {
>   printf("Hello world\n");
> }
> EOF
$ ./tst
Hello world
3
  • This looks a little easier to use. Thanks as well! Jan 18, 2010 at 4:49
  • How do u edit the previous multilineS? For example how would I type ` int main(void) { } ` and then go back afterwards and add in printf("etc"); ni the line before? Apr 27, 2020 at 6:53
  • @bluejayke u cant
    – TheEagle
    Jan 23, 2021 at 17:22
6

I confess to sometimes highlighting code and using:

(cat preamble.hpp; xsel) | g++ -x c++ - && ./a.out

The same works with "-x c" for C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.