development

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

big-blog 2020. 6. 2. 08:18
반응형

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() {

}

header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.

client.h

#ifndef CLIENT_H
#define CLIENT_H

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


#endif /** CLIENT_H */

Then you'd implement the .h in a .c file like so:

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

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

반응형