简体   繁体   English

运行时在c源代码中编译另一个源代码

[英]Compile another source code in c source code during runtime

This is an extremely weird question, but I am still curious.这是一个非常奇怪的问题,但我仍然很好奇。 I have a source code ac , in it, I have some magic code that compiles a different code bc in the same directory.我有一个源代码ac ,其中有一些魔术代码可以在同一目录中编译不同的代码bc Hence, during runtime, bc is compiled and perhaps ran.因此,在运行时, bc被编译并可能运行。

I apologize for this question to be vague, but is this something that's been done before?我很抱歉这个问题含糊不清,但这是以前做过的事情吗? If not, is there any way to do so?如果没有,有什么办法可以做到吗?

ac :交流

#include <stdio.h>

int main() {
    puts("a: compiling b.c");
    system("gcc -o b b.c");
    puts("a: executing b");
    system("./b");
    puts("a: done");
    return 0;
}

bc :公元前

#include <stdio.h>

int main() {
    puts("b: hello world");
    return 0;
}

output :输出

a: compiling b.c
a: executing b
b: hello world
a: done

Yes, you can fork and exec to run the compiler, and then fork and exec again to run the compiled code.是的,您可以forkexec运行编译器,然后再次forkexec运行编译后的代码。 The other option is to use the system function to run the compiler, and then call system again to run the compiled code.另一种选择是使用system函数运行编译器,然后再次调用system运行编译后的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM