C编程 - 编写自己编译的文本文件

Fra*_*lea 3 c compiler-construction writing file cc

我正在尝试将文件写入磁盘,然后自动重新编译.不幸的是,似乎没有用,我收到的错误信息我还不明白(我是C初学者:-).如果我手动编译生成的hello.c,它一切正常吗?!

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

    int main()
    {
        FILE *myFile;
        myFile = fopen("hello.c", "w");
        char * text = 
        "#include <stdio.h>\n"
        "int main()\n{\n"
        "printf(\"Hello World!\\n\");\n"
        "return 0;\n}";
        system("cc hello.c -o hello");
        fwrite(text, 1, strlen(text), myFile);  
        fclose(myFile);
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crt1.o:在函数_start': (.text+0x20): undefined reference tomain中'collect2:ld返回1退出状态

pax*_*blo 5

这是因为在编写程序源代码之前,您正在调用system编译文件.因为,在那一点上,你的文件是一个空文件,链接器正在抱怨,这是正确的,它不包含一个函数.hello.cmain

尝试改变:

system("cc hello.c -o hello");
fwrite(text, 1, strlen(text), myFile);  
fclose(myFile);
Run Code Online (Sandbox Code Playgroud)

至:

fwrite(text, 1, strlen(text), myFile);  
fclose(myFile);
system("cc hello.c -o hello");
Run Code Online (Sandbox Code Playgroud)