2011-04-16 71 views
3

我正在嘗試將文件寫入磁盤,然後自動重新編譯該文件。不幸的是,這似乎不起作用,我得到一個錯誤信息,我還不明白(我是一個C初學者:-)。如果我手動編譯生成的hello.c,它一切正常?!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; 
    } 

這是我的錯誤:

/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crt1的.o:在功能_start': (.text+0x20): undefined reference to主 collect2:LD返回1個退出狀態

+0

在編寫文件之前編譯文件?所以這個文件是空的,然後你編譯它,並且gcc給出正確的錯誤,文件中沒有主函數。 – 2014-08-10 16:31:19

回答

5

這是因爲你調用system你寫的程序源代碼,它之前對文件進行編譯。而且,因爲在那個時候,你的hello.c是一個空文件,所以鏈接器正在抱怨,它不包含main函數。

嘗試改變:

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

到:

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

嘿,非常感謝,它現在有效。另外,我是否需要爲strlen添加一個額外的+1或者沒有必要? – 2011-04-16 13:37:45

+0

@Frank:不,那會在文件末尾放置一個NULL字節,這可能會影響一些編譯器。只寫出字符串的長度是很好的,儘管我會在最後的(})之後(個人)添加一個'\ n'。換句話說:'「return 0; \ n} \ n」;' – paxdiablo 2011-04-16 13:39:29

+0

好的,非常感謝您的幫助! – 2011-04-16 13:42:57

0

你試圖編譯文件編寫了文件之前?

0

在調用系統來編譯文件之前,您不應該先寫入文件並關閉文件嗎?我相信這是你的問題。