When you include the header file in C, does it automatically include the .c file with the same name?

I looked on the Internet in the same way as in my textbook, and it scares 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.

Thus, it includes prototypes, but how does it implement their implementation? The header files do not seem to require you to #include stack.c with them. Is it just looking for all .c files in one folder and trying to find them?

+6
source share
5 answers

Not; it includes only the title.

You compile the source separately and link it to your code that uses it.

For example (toy code):

stack.h

 extern int pop(void); extern void push(int value); 

stack.c

 #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"); } 

test.c

 #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); } 

Compilation

 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 create object files) and link them. Often, the stack.o file stack.o placed in a library (other than the standard C library), and you link to that library. This is what happens with the standard C library functions, of course. The C compiler automatically adds the C library (usually -lc ) to the bind command.

+9
source

The title is only required to obtain prototypes. The implementation is compiled separately and assembled into a ready-made library or executable file using linker .

+1
source

Header files ( *.h ) are for compiler support only. Individual source files are included together using the linker. Any basic C development tutorial should cover this, but there is a decent โ€œtutorialโ€:

http://www.tenouk.com/ModuleW.html

0
source

You need to compile test.c by producing test.o, compile stack.c by creating stack.o, and at some point link the .o files to create a complete program.

0
source

Not. You must compile and link the .c files.

0
source

Source: https://habr.com/ru/post/912708/


All Articles