-
Header files question
In response to one of my Cboard queries I was told by a responding OP that my header file treatment was wrong. The way I did it, was conform an Internet tutorial. This is how (re below). Please tell me what is wrong and also how it should be done. I understand that the "externs" in the example signify that no memory is to be allotted. I was also told that no function definitions should be in a header file. Where then should they be defined?
Code:
//in foo.h
#ifndef temp
#define temp
extern int foo(int x)
#end if
extern int foo(int x)
{
return x+5;
}
//in main.c
#include "foo.h"
int main(void)
{
int y = foo(3);
printf("%d\n",y)
}
-
The conventional way is to put declarations in a header file and definitions in a source file:
foo.h:
Code:
#ifndef FOO_H
#define FOO_H
// declarations
extern int myvariable;
int foo(int x);
#endif
foo.c:
Code:
#include "foo.h"
// definitions
int myvariable;
int foo(int x)
{
return x+5;
}
main.c:
Code:
#include <stdio.h>
#include "foo.h"
int main(void)
{
int y = foo(3);
printf("%d\n",y)
}
"extern" means "this object is declared here but defined elsewhere". It's usually used to declare variables in a header file. It's optional (that is, it's not needed) for function declarations.
-
[QUOTE=christop;1292211]The conventional way , <snipped>
What you say is clear. Thank you. The strange thing is that I have an application where that approach errors out. But there are more peculiarities with that code.