为什么我会收到“使用未声明的标识符'malloc'”的错误提示?

8

我正在尝试使用XCode编译别人的Windows代码。

有这样一个问题:

inline GMVariable(const char* a) {
    unsigned int len = strlen(a);
    char *data = (char*)(malloc(len+13));
    if(data==NULL) {
    }
    // Apparently the first two bytes are the code page (0xfde9 = UTF8)
    // and the next two bytes are the number of bytes per character (1).
    // But it also works if you just set it to 0, apparently.
    // This is little-endian, so the two first bytes actually go last.
    *(unsigned int*)(data) = 0x0001fde9;
    // This is the reference count. I just set it to a high value
    // so GM doesn't try to free the memory.
    *(unsigned int*)(data+4) = 1000;
    // Finally, the length of the string.
    *(unsigned int*)(data+8) = len;
    memcpy(data+12, a, len+1);
    type = 1;
    real = 0.0;
    string = data+12;
    padding = 0;
}

这是一个头文件。

它会提示:

使用了未声明的标识符 'malloc'

还有strlen,memcpy和free。

发生了什么?如果这很简单,请原谅,我是C和C++的新手。


@WillAyd 我刚刚加入了它,现在错误只剩下strlen和memcpy了。谢谢,但这两个怎么办? - Name McChange
2个回答

22

XCode提示你正在使用malloc,但它不知道malloc是什么。最好的方法是将以下内容添加到你的代码中:

#include <stdlib.h> // pulls in declaration of malloc, free
#include <string.h> // pulls in declaration for strlen.

C和C++中以#开头的行是预处理器的命令。在这个例子中,命令#include引入了另一个文件的全部内容。就好像你自己键入了stdlib.h的内容一样。如果右键点击#include行并选择“转到定义”,XCode将打开stdlib.h。如果你在stdlib.h中搜索,你会发现:

void    *malloc(size_t);

这告诉编译器,malloc是一个可以使用单个size_t参数调用的函数。

您可以使用“man”命令查找要包含哪些头文件以供其他函数使用。


s/definitions/declarations/ 的含义是“将'定义'替换为'声明'”。 - R.. GitHub STOP HELPING ICE

9
在使用这些函数之前,您应该包含提供其原型的头文件。
对于malloc和free,它们是:
#include <stdlib.h>

对于 strlen 和 memcpy,它们的意思分别是:

#include <string.h>

您也提到了C ++。 这些功能来自C标准库。 要从C ++代码中使用它们,请包含以下行:
#include <cstdlib>
#include <cstring>

然而,在C++中,您可能会以不同的方式完成任务,并且不会使用这些技术。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接