Compile string of C code

痞子三分冷 提交于 2019-12-09 12:44:55

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/2083874/compile-string-of-c-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!