2012-09-03 31 views
6

我正在嘗試使用XCode並嘗試編譯別人的Windows代碼。爲什麼我會得到「使用未聲明的標識符'malloc'」?

有這樣的:

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和自由。

發生了什麼事?對不起,如果這很簡單,我是C和C++新手

+1

你是否包含stdlib.h? –

+0

@WillAyd我只是將它包括在內,現在錯誤簡化爲strlen和memcpy。謝謝,但這兩個呢? –

回答

18

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」命令查找要爲其他功能包含哪些頭文件。

+0

's/definitions/declarations /'。 –

+0

你是對的!固定。 – razeh

4

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

的malloc的&免費是:

#include <stdlib.h> 

函數strlen和memcpy是:

#include <string.h> 

你還別說C++。這些功能來自C標準庫。從C++代碼使用它們包括線路將是:

#include <cstdlib> 
#include <cstring> 

然而,你可能會以不同方式使用C做事++和不使用這些。

相關問題