Creating your own header file in C

Anuragdeb3 picture Anuragdeb3 · Aug 18, 2011 · Viewed 335.3k times · Source

Can anyone explain how to create a header file in C with a simple example from beginning to end.

Answer

Oliver Charlesworth picture Oliver Charlesworth · Aug 18, 2011

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

To compile using GCC

gcc -o my_app main.c foo.c