I want to be able to create a collection of functions in a header file that I could #include in one of my C Programs.
- Open your favorite text editor
- Create a new file named whatever_you_want.h
- Put your function prototypes in it
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
Keep in mind that you can also place the header file in another director so long as you give the path in the include statement. Just make sure you keep the path relative instead of absolute. That way your code remains portable.
For example:
include "../my_headers_directory/whatever.h"
tells the program to include whatever.h that in the parent directory's my_headers_director.