2012-09-03 5 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; 
} 

これは、ヘッダファイルです。

それはmemcpyを、自由、

ものためのstrlen関数宣言されていない識別子 'のmalloc' の

使用上の私を呼び出します。

何が起こっているのですか?申し訳ありませんが、これは痛いほどシンプルですが、私はCとC++を初めて使用しています

+1

あなたはstdlib.hを含んでいますか? –

+0

@WillAyd私はそれを含めたところで、エラーはstrlenとmemcpyに短縮されました。ありがとう、しかし、これらの2はどうですか? –

答えて

18

XCodeは、mallocと呼ばれるものを使用していると伝えていますが、mallocが何であるかは分かりません。これを行うための最善の方法は、あなたのコードに以下を追加することです:CおよびCでは

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

++#で始まる行はプリプロセッサにコマンドです。この例では、#includeコマンドは別のファイルの完全な内容を取得します。 stdlib.hの内容を自分で入力したかのようになります。 #include行を右クリックして「定義に移動」を選択すると、XCodeがstdlib.hを開きます。あなたはSTDLIB.Hを検索した場合、あなたは見つけることができます:

malloc関数を使用すると、単一size_tの引数で呼び出すことができる機能であることをコンパイラに指示します
void *malloc(size_t); 

「man」コマンドを使用して、他の機能に含めるヘッダーファイルを見つけることができます。

+0

's/definitions/declarations /'です。 –

+0

あなたは正しいです!一定。 – razeh

4

これらの機能を使用する前に、プロトタイプを提供するヘッダーファイルを含める必要があります。 malloc関数&ため

それは自由:strlenのため

#include <stdlib.h> 

、それをmemcpyのは、次のとおりです。

#include <string.h> 

また、C++に言及。これらの関数は、C標準ライブラリの関数です。インクルードは、行を含めるC++コードからそれらを使用するには、次のようになります。

#include <cstdlib> 
#include <cstring> 

しかし、あなたもCで違うことをやっているかもしれません++およびこれらを使用していません。

関連する問題