为什么我会"使用未声明的标识符'malloc'"?

Nam*_*nge 8 c xcode

我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)

这是在头文件中.

它叫我出去

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

而且对于strlen,memcpy和free.

这是怎么回事?对不起,如果这很简单,我是C和C++的新手

raz*_*zeh 20

XCode告诉你,你正在使用一个名为malloc的东西,但它不知道malloc是什么.最好的方法是在代码中添加以下内容:

#include <stdlib.h> // pulls in declaration of malloc, free
#include <string.h> // pulls in declaration for strlen.
Run Code Online (Sandbox Code Playgroud)

在以#开头的C和C++行中是对预处理器的命令.在此示例中,命令#include将提取另一个文件的完整内容.就好像你自己输入了stdlib.h的内容一样.如果右键单击#include行并选择"转到定义",XCode将打开stdlib.h.如果你搜索stdlib.h,你会发现:

void    *malloc(size_t);
Run Code Online (Sandbox Code Playgroud)

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

您可以使用"man"命令查找要包含在其他函数中的头文件.


Avi*_*ger 5

在使用这些函数之前,您应该包含提供其原型的头文件.

对于malloc和免费它是:

#include <stdlib.h>
Run Code Online (Sandbox Code Playgroud)

对于strlen和memcpy,它是:

#include <string.h>
Run Code Online (Sandbox Code Playgroud)

你还提到了C++.这些函数来自C标准库.要从C++代码中使用它们,include行将是:

#include <cstdlib>
#include <cstring>
Run Code Online (Sandbox Code Playgroud)

但是,你很可能在C++中做不同的事情,而不是使用它们.