我正在尝试将文件写入磁盘,然后自动重新编译。不幸的是,某事似乎不起作用,我收到一条我还不明白的错误消息(我是 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;
}
这是我得到的错误:
/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crt1.o: 在函数 _start':
(.text+0x20): 对
main' 的 undefined reference
collect2: ld 返回 1 个退出状态
最佳答案
这是因为您在编写程序源代码之前调用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");
关于C 编程 - 编写可自行编译的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5686816/