开发者

Compile string of C code

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 l开发者_运维问答ines 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜