source

C에 자체 헤더 파일 생성

itover 2022. 11. 22. 21:30
반응형

C에 자체 헤더 파일 생성

C에 헤더 파일을 작성하는 방법을 처음부터 끝까지 간단한 예시로 설명할 수 있는 사람이 있습니까?

후우

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

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

#endif // FOO_H_

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

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

메인

#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*);

필요한 경우 파라미터의 식별자를 포함할 수도 있지만, 이 식별자는 함수 본문(실장)에서만 사용되기 때문에 필요하지 않습니다.헤더(파라미터 시그니처)의 경우 해당 식별자가 누락됩니다.

그러면 함수가 선언됩니다.foo이 경우,char*및 반환한다.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를 두 번 포함할 경우 프로토타입이 한 번만 포함되도록 할 수 있습니다.

클라이언트.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 파일로 구현합니다.

클라이언트

#include "client.h"

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
 short ret = -1;
 //some implementation here
 return ret;
}

언급URL : https://stackoverflow.com/questions/7109964/creating-your-own-header-file-in-c

반응형