Creating your own header file in 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;}
To compile using 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
serves as a double-inclusion guard.
For the function declaration, you only need to define the signature, that is, without parameter names, like this:
int foo(char*);
If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.
This declares the function foo
which accepts a char*
and returns an int
.
In your source file, you would have:
#include "my_header.h"int foo(char* name) { //do stuff return 0;}
myfile.h
#ifndef _myfile_h#define _myfile_hvoid function();#endif
myfile.c
#include "myfile.h"void function() {}