簡體   English   中英

為什么我會“使用未聲明的標識符'malloc'”?

[英]Why am I getting “Use of undeclared identifier 'malloc' ” ?

我正在嘗試使用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 ++的新手

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”命令查找要包含在其他函數中的頭文件。

在使用這些函數之前,您應該包含提供其原型的頭文件。

對於malloc和免費它是:

#include <stdlib.h>

對於strlen和memcpy,它是:

#include <string.h>

你還提到了C ++。 這些函數來自C標准庫。 要從C ++代碼中使用它們,include行將是:

#include <cstdlib>
#include <cstring>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM