I've looked around online as well as in my textbook and this is confusing me.
Say you have some functions for stacks in stack.c, and you put their prototypes in stack.h. Your main program, say, test.c has #include "stack.h"
at the top. This is how all the examples show.
So it includes the prototypes, but how does it get their implementations? The header files don't seem to require that you #include stack.c
with them. Does it just search all the .c files in the same folder and try to find them?
The answer to the above is yes. header files are simply files in which you can declare your own functions that you can use in your main program or these can be used while writing large C programs. NOTE:Header files generally contain definitions of data types, function prototypes and C preprocessor commands.
It attempts to find a function definition (implementation), which exactly matches the header you declared earlier. What happens if you #include header file is that compiler (specifically, the preprocessor) copies the whole contents of header file into place, where you put your #include .
Rationale. In the C and C++ programming languages, a header file is a file whose text may be automatically included in another source file by the C preprocessor by the use of a preprocessor directive in the source file.
You don't have to, but you can. The header file contains the declarations. You're free to invoke anytime as long as the prototype matches. And as long as the compiler finds an implementation before finishing compilation.
No; it includes just the header.
You compile the source separately, and link that with your code that uses it.
For example (toy code):
extern int pop(void);
extern void push(int value);
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
enum { MAX_STACK = 20 };
static int stack[MAX_STACK];
static int stkptr = 0;
static void err_exit(const char *str)
{
fprintf(stderr, "%s\n", str);
exit(1);
}
int pop(void)
{
if (stkptr > 0)
return stack[--stkptr];
else
err_exit("Pop on empty stack");
}
int push(int value)
{
if (stkptr < MAX_STACK)
stack[stkptr++] = value;
else
err_exit("Stack overflow");
}
#include <stdio.h>
#include "stack.h"
int main(void)
{
for (int i = 0; i < 10; i++)
push(i * 10);
for (int i = 0; i < 10; i++)
printf("Popped %d\n", pop());
return(0);
}
c99 -c stack.c
c99 -c test.c
c99 -o test_stack test.o stack.o
Or:
c99 -o test_stack test.c stack.c
So, you compile the source files (optionally producing object files) and link them. Often, the stack.o
file would be placed into a library (other than the standard C library) and you'd link with that library. This is what happens with the standard C library functions as well, of course. The C compiler automatically adds the C library (usually -lc
) to the linking command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With