Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is recommended way to create modular C applications? [closed]

Tags:

c

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?

like image 846
Bracketz Avatar asked Nov 11 '15 09:11

Bracketz


People also ask

How can we achieve modular programming in c?

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.

What do you mean by modular programming in c?

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.


1 Answers

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 called bit.h containing all global variables and function prototypes from bit.c and then include it into demo.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.

like image 69
Magisch Avatar answered Nov 15 '22 18:11

Magisch