204

最初から最後まで簡単な例を使用して、C でヘッダー ファイルを作成する方法を誰でも説明できますか。

4

4 に答える 4

348

foo.h

#ifndef FOO_H_   /* Include guard */
#define FOO_H_

int foo(int x);  /* An example function declaration */

#endif // FOO_H_

foo.c

#include "foo.h"  /* Include the header (not strictly necessary here) */

int foo(int x)    /* Function definition */
{
    return x + 5;
}

main.c

#include <stdio.h>
#include "foo.h"  /* Include the header here, to obtain the function declaration */

int main(void)
{
    int y = foo(3);  /* Use the function here */
    printf("%d\n", y);
    return 0;
}

GCCを使用してコンパイルするには

gcc -o my_app main.c foo.c
于 2011-08-18T15:31:51.793 に答える
31
#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_Hダブルインクルージョンガードとして機能します。

関数宣言の場合、次のように、署名を定義するだけで済みます。つまり、パラメーター名はありません。

int foo(char*);

本当に必要な場合は、パラメーターの識別子を含めることもできますが、識別子は関数の本体(実装)でのみ使用され、ヘッダー(パラメーターの署名)の場合は欠落しているため、必須ではありません。

これは、を受け入れて返す関数を宣言します。foochar*int

ソースファイルには、次のものがあります。

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}
于 2011-08-18T15:31:50.693 に答える
10

myfile.h

#ifndef _myfile_h
#define _myfile_h

void function();

#endif

myfile.c

#include "myfile.h"

void function() {

}
于 2011-08-18T15:34:11.100 に答える
8

ヘッダーファイルには、.cまたは.cpp / .cxxファイルで定義した関数のプロトタイプが含まれています(cまたはc ++のどちらを使用しているかによって異なります)。.hコードの周りに#ifndef /#definesを配置して、プログラムの異なる部分に同じ.hを2回含めた場合に、プロトタイプが1回だけ含まれるようにします。

client.h

#ifndef CLIENT_H
#define CLIENT_H

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);


#endif /** CLIENT_H */

次に、次のように.hを.cファイルに実装します。

client.c

#include "client.h"

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
 short ret = -1;
 //some implementation here
 return ret;
}
于 2011-08-18T15:32:27.410 に答える