Creating your own header file in C
Asked Answered
A

4

238

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

Ahner answered 18/8, 2011 at 15:25 Comment(1)
Have you read an introductory book on C? Here's an online one: publications.gbdirect.co.uk/c_book.Dandrea
D
405

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
Dandrea answered 18/8, 2011 at 15:31 Comment(9)
@Anu: I can't read that in this format. You could edit your original question to include this code.Dandrea
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.Kinglet
@Jeyekomon: Well, where is the problem?Dandrea
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.Kinglet
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 mindObstacle
@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?Kopeisk
@Obstacle you can #include "foo.c" inside main.c to accomplish that but doing so is not a good practiceMorly
(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!!Tameika
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)Triclinic
E
37
#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;
}
Estonian answered 18/8, 2011 at 15:31 Comment(6)
They're known as function declarations or function prototypes, not "function headers". Headers are the files you include, not the declarations inside them.Attractant
@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.Estonian
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, for example.Attractant
@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.Estonian
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 <stdio.h>."Attractant
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.Attractant
S
10

myfile.h

#ifndef _myfile_h
#define _myfile_h

void function();

#endif

myfile.c

#include "myfile.h"

void function() {

}
Salute answered 18/8, 2011 at 15:34 Comment(5)
void function(); as a declaration does not prevent calls like function(42);. Use void in the declaration like void function(void);Coprology
@chux-ReinstateMonica why WHY would that be allowed? What kind of use-case would warrant allowing such a definition and call signature?? (Genuinely curious)Triclinic
@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.Coprology
@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?Triclinic
@RandomnessSlayer Unclear why the comment parameterless function with parameters would decrease memory overhead. 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.Coprology
G
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;
}
Gav answered 18/8, 2011 at 15:32 Comment(2)
"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.Attractant
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?Propertied

© 2022 - 2024 — McMap. All rights reserved.