开发者

C Programming - Writing text file that compiles itself

I'm trying to write a file to disk that gets then recompiled automatically. Unfortunately, sth does not seem to work and I'm getting an error message I don't yet understand (I'm a C Beginner :-). If I compile the produced hello.c manually, it all works?!

#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);
        r开发者_开发问答eturn 0;
    }

This is the error I get:

/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crt1.o: In function _start': (.text+0x20): undefined reference tomain' collect2: ld returned 1 exit status


It's because you're calling system to compile the file before you've written the program source code to it. And because, at that point, your hello.c is an empty file, the linker is complaining, rightly so, that it doesn't contain a main function.

Try changing:

system("cc hello.c -o hello");
fwrite(text, 1, strlen(text), myFile);  
fclose(myFile);

to:

fwrite(text, 1, strlen(text), myFile);  
fclose(myFile);
system("cc hello.c -o hello");


You're trying to compile the file before you've written the file?


Shouldn't you write the file and close the file first before you call system to compile the file? I believe this is your problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜