i want create a header file in C-programming and add it to library to use. Please could you help me.
+1
A:
Create a file with the extension .h
, for example mystuff.h
. Put the desired header contents in there, and include it in your sources via #include "mystuff.h"
.
Matt Joiner
2010-08-12 16:53:25
This could get messy, depending on the include paths and where the header is stored. Such is C.
strager
2010-08-12 16:55:24
Luckily, it's C. It could be worse.
Matt Joiner
2010-08-12 18:11:39
+1
A:
Some header:
//header.h
#ifndef HEADER_H
#define HEADER_H
int ThisReturnsOne() {
return 1;
}
#endif //HEADER_H
Some c file:
//file.c
#include "header.h"
int main() {
int x;
x = ThisReturnsOne(); //x == 1
}
So the contents of "header.h" are available to "file.c". This assumes they are in the same directory.
Edit: Added include guards. This prevents the header file from being included in the same translation unit twice.
eldarerathis
2010-08-12 16:54:48
No include guards? I suggest you add them to your example, as it's a best practice. EDIT: Thanks.
strager
2010-08-12 16:55:54
It was an exceptionally trivial example off the top of my head. Added them now, though.
eldarerathis
2010-08-12 16:57:54
"Edit: Added include guards. This prevents the header file from being included in the same project twice." Correction: "in the same *translation unit* twice". This basically means "in the same compiler invocation".
strager
2010-08-12 17:36:25
@strager To be pedantic, no it doesn't - `mycc a.c b.c` is two translation units, one compiler invocation.
anon
2010-08-12 18:18:53
@Neil Butterworth, Yes, I know that. I used 'basically' to mean 'this is probably how you think of it when compiling, but it's a simplified view which is technically incorrect'.
strager
2010-08-12 18:55:12