The header file (.h
) is the programmer's interface to your module. Anything a user (programmer) of your module needs to know to use your module should be in there, but put the actual implementations in the associated .c
file. Generally, you put the function prototypes (e.g. int f(void);
) in the .h
file and the definitions (the implementations, e.g. int f(void) { return 1; }
) in the .c
file. The linker matches the prototype to the definition because the function signatures match (the name, argument types, and return type). One way to think about it is the .h
file as what you share with everyone, and the .c
file as what you keep to yourself.
If you want a user of your module to have access to STUDENT_SIZE
, then put
#define STUDENT_SIZE 20
in your .h
file instead of your .c
file. Then, any file with
#include "stud.h"
would have your macro for STUDENT_SIZE
. (Notice the file name is "stud.h"
not "stud"
.)
Lets say i want to use STUDENT_SIZE in another file whats the syntax? Do i need to use stud.STUDENT_SIZE?
No. You might be confusing this with namespaces, which C does not have in the same sense as other languages like C++, Java, etc. Just use STUDENT_SIZE
. (This is why it is important to not use existing identifiers, and also why many people frown upon macros.)
... i want from another file to access some of the functions inside stud.c.
If you want another file to have access to some function in stud.c
, then put that function's prototype in stud.h
. This is precisely what the header file is for.
... if i want to lets say make an array of students:
struct stud students[STUDENT_SIZE];
Can i access that normally like students[5].stud_id
?
As you have written your header file, no. You might know some struct stud
exists, but you don't know what the members are called (i.e. you wouldn't know stud_id
exists). The reason is that the user of your module sees only what is in the header file, and you defined no members of the struct in your header file. (I'm surprised what you have written even compiles, because you define struct stud
twice, once empty {}
, and once with members.) Again, if you want the programmer user to have access to the members of struct stud
, its definition
struct stud {
char stud_id[MAX_STR_LEN];
char stud_name[MAX_STR_LEN];
struct grade Grade[MAX_STRUCT];
struct income Income[MAX_STRUCT];
};
belongs in your header file (along with whatever those other macros are). Without knowing this, the programmer (and the compiler) has no idea what the members of struct stud
are.
(You didn't ask about this, but if you want to share access to a global variable in your .c
file, then declare it with the keyword extern
in your .h
file, and without extern
in your .c
file. See How to correctly use the extern keyword in C for more.)