I read in Stack Overflow that including a C file into another C file is not a best practice. I was wondering how can I then create modular applications in C.
I understood that all you are recommended to include are header files, which doesn't contain the code implementation itself but just the "function calls".
How does the compiler know where to find the respective code? Does it automatically look to a .c file with same name as the .h file?
Generally speaking, how can separate code within a C application?
Modular programming consists of separating implementation from interface and hiding information in the implementation. In C this is achieved by placing the interface definition in a header file and the implementation in a source file. Disciplined use of static is used to hide implementation details.
Modular programming is the process of subdividing a computer program into separate sub-programs. A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system.
Generally speaking inlcuding header files instead of complete c files is best practice yes. Your compiler does not need to know where any other code is, just the prototypes of the functions used.
The part of the process that needs to know where the other code is is the Linker, which is not the compiler, but included in complete solutions like gcc.
When compiling in gcc for instance, you can add references for the linker, as specifically noted in the comments.
Credit to @jovit.royeca for an example on linking with the compiler gcc:
Suppose you have a main file for your program called
demo.c
You are using some functions of the file
bit.c
in it. What you then need to do is make a header calledbit.h
containing all global variables and function prototypes frombit.c
and then include it intodemo.c
with#include "bit.h"
and then link it in gcc like so:
gcc -o demo demo.c bit.c
Some complete solutions like eclipse for c/c++ automatically assume all c files in a project will be linked to the main one, for instance.
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