jweinst1
1/8/2019 - 9:06 PM

run a string of c source code with gcc in C

run a string of c source code with gcc in C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

const char *prog = "#include <stdio.h>\nint main(void) {puts(\"foo\"); return 0;}";

int main() {
    FILE *proc = popen("gcc -x c -", "w");
    if(!proc) {
        perror("popen gcc");
    }
    fwrite(prog, sizeof(char), strlen(prog), proc);
    if(ferror(proc)) {
        perror("writing prog");
    }
    if(pclose(proc) == -1) {
        perror("pclose gcc");
    }
    system("./a.out");
    remove("a.out");
}