[c] C에서 자신의 헤더 파일 만들기

누구나 간단한 예제를 통해 C에서 헤더 파일을 만드는 방법을 처음부터 끝까지 설명 할 수 있습니다.



답변

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


답변

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H 이중 포함 가드 역할을합니다.

함수 선언의 경우 다음과 같이 서명, 즉 매개 변수 이름없이 만 정의하면됩니다.

int foo(char*);

실제로 원하는 경우 매개 변수의 식별자를 포함 할 수도 있지만 식별자는 함수 본문 (구현)에서만 사용되므로 헤더 (매개 변수 서명)의 경우 누락되기 때문에 필요하지 않습니다.

이것은 a를 받아들이고 a 를 반환하는 함수 를 선언 합니다 .foochar*int

소스 파일에는 다음이 있습니다.

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}


답변

myfile.h

#ifndef _myfile_h
#define _myfile_h

void function();

#endif

myfile.c

#include "myfile.h"

void function() {

}


답변

헤더 파일에는 .c 또는 .cpp / .cxx 파일에서 정의한 함수의 프로토 타입이 포함되어 있습니다 (c 또는 c ++를 사용하는 경우에 따라 다름). 프로그램의 다른 부분에 동일한 .h를 두 번 포함하면 프로토 타입이 한 번만 포함되도록 # ifndef / # defines를 .h 코드 주위에 배치하려고합니다.

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;
}


답변