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

13

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
Sign up to request clarification or add additional context in comments.

5 Comments

This looks a little easier to use. Thanks as well!
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?
@bluejayke u cant
I couldn't get this to work. I then tried a simpler example, g++ -x c++ - << "int main(){}", which needs me to end the input with CTRL+D; then producing a warning from bash (here-document at line 123 delimited by end-of-file (wanted int main(){})), and a link error from GCC (undefined reference to main).
@user2023370 If you want to use a simple string instead of a "here-document", you need to use <<< like this: g++ -x c++ -o tst - <<< "int main() {}"
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.