cfilecompiler-constructioncc

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);
        return 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


Solution

  • 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");