C 编程 - 编写可自行编译的文本文件

标签 c file compiler-construction 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;
    }

这是我得到的错误:

/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/

相关文章:

C 函数 read() 导致命令注入(inject)

c - 如何读取文件 C,fscanf 结尾

java - 文件是目录还是普通文件?

c++ - 为什么 basic_ifstream 显示错误的结果?

c++ - 增加堆栈不起作用

JAVA 编译器 API - 无法找到外部类文件

c - 使用 scanf() 读取一行不好吗?

在 Mac OS X 上找不到 C 头文件

c - C 中的哈希宏定义

c - 自动生成 C 结构构造函数?