Reputation: 11
I am new compiling with multiple files and I am finding it so confusing to grasp.
Ok, so suppose I have a party.c which I want to inherit functions from two programs: decorations.c, food.c.
I learned that its not good practice to include .c files in the #include statements so I've created header files and add them to party.c:
#include "decorations.h"
#include "food.h"
Now, decorations.c has the following includes:
#include "decoration.h"
#include "food.h"
And food.c has the following includes:
#include "food.h"
One more thing. Suppose that I have lights.c which includes:
#include "decorations.h"
And I also need a function in lights.c for party.c. Do I HAVE to create a header file for lights.c too? How can I compile this?? How can I write my makefile? Or compile this without a makefile?
I'm sorry if this is really basic..
Upvotes: 0
Views: 255
Reputation: 101
Ok, so suppose I have a party.c which I want to inherit functions from two programs: decorations.c, food.c
So basically, you want to use the functions in "decorations.c" and "food.c" in the file "party.c"?
I think you should just compile all of them together. Like so:
gcc -ansi -Wall -pedantic party.c decorations.c food.c -o program
I am assuming that you have all the functions you need in the header files "decorations.h", "food.h". If not, create another header file with the missing functions. I always feel that including more than 1 header file in a .c file is a bad idea.
Hope this helps!
Upvotes: 0
Reputation: 45654
Generally, you create a header-file for related functionality with possibly related implementations.
While you can certainly have one implementation-file per header-file, it is not that uncommon to split the implementation of the interface declared in the header-file over multiple implementation-files.
Also, using a private header for a set of implementation-units (or for your whole library), in addition to the public header-files is common to improve encapsulation.
Next, it is quite common for the main implementation-file not to provide a (public or private) interface and thus no headers, but only to consume other headers.
Last, it is your responsibility and decision to partition your project in whatever way makes sense, which might mean not having multiple files at all.
The advantages of proper partitioning / encapsulation are increased re-usability, reduced coupling, faster compilation and making things easier understandable to humans.
Upvotes: 2