226

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

Lundin
  • 195,001
  • 40
  • 254
  • 396
Anuragdeb3
  • 2,299
  • 3
  • 14
  • 4

4 Answers4

389

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
umlcat
  • 4,091
  • 3
  • 19
  • 29
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 2
    @Anu: I can't read that in this format. You could edit your original question to include this code. – Oliver Charlesworth Aug 18 '11 at 16:54
  • 3
    It's worth noting that this code doesn't work if you try to just build it by button ("build and run" in Code::Blocks for example). It might seem obvious for you but for me it's the first time it has happened and it took me quite some time to figure out where is the problem. – Jeyekomon Jun 07 '14 at 18:15
  • 6
    @Jeyekomon: Well, where *is* the problem? – Oliver Charlesworth Jun 07 '14 at 18:16
  • 2
    Noone has told me that the "build and run" button isn't sufficient for everything. :-) It was quite a surprise for me (i'm a newbie). Now I guess I have to learn to use the commandline or makefiles first. – Jeyekomon Jun 07 '14 at 18:26
  • 1
    I was wondering if you could elaborate on how to compile with all required files and not have to include foo.c into gcc program argument. What is this technique called or what program can accomplish this outside of IDE - Make comes to my mind – nf071590 Oct 09 '14 at 22:31
  • 1
    @nf071590: Using `make`, you'd (presumably) still be using `gcc` or `cc`, and you would still need to tell `make` to tell either compiler which files were needed. Why do you wish to avoid providing "foo.c" to the compiler? – eenblam May 28 '15 at 22:19
  • 1
    @nf071590 you can #include "foo.c" inside main.c to accomplish that but doing so is not a good practice – avm May 27 '21 at 20:47
  • 1
    `(not strictly necessary here)` **Balderdash! Rubbish!** If not included in translation unit where function is defined, the prototype could say one thing and the func definition something altogether different... ALWAYS include the header when call-er and call-ee must agree on function signatures... ALWAYS!! That is their sole purpose for existence!! – Fe2O3 Sep 09 '22 at 08:14
  • If `main.c`, `foo.c`, and `foo.h` are local (in this case they are; note the quotes on `#include "foo.h"`), it should suffice to use the command: `gcc -o my_app main.c` (without `foo.c`; with `foo.h` in scope already in `main.c`, gcc can find `foo.c` to bring in the implementation) – Randomness Slayer Oct 04 '22 at 18:35
36
#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;
}
Flavius
  • 13,566
  • 13
  • 80
  • 126
  • 1
    They're known as function _declarations_ or function _prototypes_, not "function headers". Headers are the files you include, not the declarations inside them. – Jonathan Wakely Apr 05 '19 at 10:36
  • @JonathanWakely Those are the header files. The name tells it all: header files contain headers. But thanks for the feedback, it made me think for a second. – Flavius Apr 08 '19 at 08:05
  • 1
    Nope, headers are the files themselves, not the declarations they contain. Can you find a single reputable reference to back up your use of "header"? It's contradicted by K&R, the C standard, _The UNIX Programming Environment_, and [Wikipedia](https://en.wikipedia.org/wiki/Include_directive#C/C++), for example. – Jonathan Wakely Apr 08 '19 at 08:33
  • @JonathanWakely have you actually read K&R? The TOC has a section "4.5 Header files" and "header files" is written in italics, indicating terminology. In the rest of the book the authors write sometimes just "header" for brevity, but through formatting and TOC it's clear what the right terminology is. So please, be a professional and recognize when you're wrong. – Flavius Apr 10 '19 at 18:41
  • 1
    Yes, and "header" refers to the **files**, not the declarations in them. In the 2nd edition see page 241 for the discussion of standard headers, and page 33 which talks about _definitions_ and _declarations_ (which you mistakenly call "function headers") and clearly defines a _header_: "The usual practice is to collect `extern` declarations of variables and functions in a separate file, historically called a _header_, that is included by `#include` at the front of each source file. The functions of the standard library, for example, are declared in headers like ``." – Jonathan Wakely Apr 10 '19 at 19:31
  • 1
    Page 26 defines _function prototype_, which is also used throughout the rest of the book, and nowhere is it interchangeable with "header". See also §A7.3.2 and §A8.6.3 for formal reference material on function declarations, which also doesn't ever call them "headers". Because that's not what they're called. – Jonathan Wakely Apr 10 '19 at 19:41
10

myfile.h

#ifndef _myfile_h
#define _myfile_h

void function();

#endif

myfile.c

#include "myfile.h"

void function() {

}
TommyGunn32
  • 924
  • 1
  • 8
  • 22
  • `void function();` as a _declaration_ does not prevent calls like `function(42);`. Use `void` in the _declaration_ like `void function(void);` – chux - Reinstate Monica May 14 '20 at 18:41
  • @chux-ReinstateMonica why WHY would that be allowed? What kind of use-case would warrant allowing such a definition and call signature?? (Genuinely curious) – Randomness Slayer Oct 04 '22 at 18:41
  • @RandomnessSlayer Strange things allowed in C are often due to historic compromises, trends and not sensible to today's standards. Often useful to recall memory was far more expensive in C's beginnings and many choices are driven by that. – chux - Reinstate Monica Nov 01 '22 at 14:15
  • @chux-ReinstateMonica if you could be so kind as to direct me to a concrete or at least anecdotal example, I would greatly appreciate it. I just don't really comprehend how calling a parameterless function with parameters would decrease memory overhead, ya know? – Randomness Slayer Nov 14 '22 at 18:58
  • @RandomnessSlayer Unclear why the comment [parameterless function with parameters would decrease memory overhead](https://stackoverflow.com/questions/7109964/creating-your-own-header-file-in-c/7110077?noredirect=1#comment131403555_7110077). Calling a parameter-less function with parameters is not an _error_, just wasteful and is more likely a coding mistake than anything useful. I see _declaration_ `void function();` allows it as that is the style of early C where a _declaration_ pretty much only told of a function name existence and return type. – chux - Reinstate Monica Nov 14 '22 at 20:14
8

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;
}
djsumdog
  • 2,560
  • 1
  • 29
  • 55
  • _"so that if you include the same .h twice in different parts of your programs, the prototypes are only included once."_ This is misleading. They guard against including the same header file twice **from the same source file** (including a header twice in two different source files is ok, and usually required!) and re-declaring function prototypes is not a problem, re-defining types and global variables is what must be guarded against. – Jonathan Wakely Apr 08 '19 at 11:45
  • This is not entirely intuitive to me - perhaps it has to do more with the specific implementation of the pre-processor that I need to understand. Why aren't the `#ifndef` and `#define` directives used in the source code for the library files (i.e., `foo.c` in the above example) rather than in the header file for that library? Is it because the compiler knows it only has one actual definition for `foo.c`? – simchuck Jul 17 '21 at 19:40