Let's suppose that I write some functions in a file, that we'll call foo.c
.
This is foo.c
:
int d;
typedef int bar;
int foo(int a, int b){
...
}
void boo(){
...
}
char *test(){
...
}
Now, boo is a function used only inside foo.c, while foo()
, test()
, d
, and Bool
will need to be able to get called inside other files.
In order to do that, I know that I have to create a foo.h
file and write it like this:
extern int d;
extern typedef int bar;
int foo(int a, int b);
char *test();
then #include "foo.h"
in the foo.c
file, and whenever I want to use the types and functions defined in foo.c, I have to include both foo.h
and foo.c
in the file in which I wanna use foo.c functions and types.
So foo.c
in the end would look like this:
#include "foo.h"
int d;
typedef int bar;
int foo(int a, int b){
...
}
void boo(){
...
}
char *test(){
...
}
Here are my questions.
Q1. Is this how you actually do it? Since foo.h
is already included in foo.c
, wouldn't it be sufficient to include only foo.c
in the file in which I want to use its functions? Can't I just directly define the functions inside of the foo.c file, not using the foo.h file at all?
Q2. Do you actually have to put the extern
in front of typedefs in the foo.h
file?
Q3. Let's say that in foo.c
I use some standard C libraries like string.h and math.h . Where should I include them? Directly in the foo.c
file, in the foo.h
file or in both? Are #ifndef
instructions necessary? If so, how do you use them correctly?
Q4. After writing the foo.c
and foo.h
file, am I all ready to go? Like, I don't need to compile them or anything, right? I can just #include
them wherever I need just like that?
Q5. Somewhere else I've read that if I want to use a custom library these are the steps that I need to follow:
- define the interface (
foo.h
) - write
foo.c
#include ingfoo.h
- creating an object file like this
gcc -o foo.o -c foo.c
- including
foo.h
in the program in which I want to usefoo.c
functions - linking the object file like this
gcc my_proj.c foo.o
Are these steps actually necessary? Because I haven't seen them mentioned anywhere else. Why do I only need to include foo.h
in the file in which I want to use foo.c
functions? What exactly is an object file?
Thanks for your time and sorry if this is a bit lengthy