Should I include a header file multiple times in different files? - c

Say, for example, that I have header files foo.h and bar.h, which both want to include hello.h, and use macros declared in hello.h. foo.h also already includes bar.h.
Should I include hello.h in both foo.h and bar.h, or just in bar.h? I know it doesn't matter functionally, but I'm not sure what the "standard" is for readability.
Edit: I know how header guards work. I'm not asking from a dependency perspective; I'm asking from a readability perspective.

You can wrap the header into preprocessor-ifs. So the compiler will handle it if you include them to often.
#ifndef _MYHEADER_
#define _MYHEADER_
// whatever
#endif

Related

How to use a .h file without header guards multiple times

Currently I have a .h file provided by a professor that I'm not allowed to modify. I have to use structures and implement the methods from the given .h file but it doesn't have header guards. I want to write a file to test the methods but am running into a typedef redefinition error when trying to include the .h file in multiple locations.
I could write all the tests in the corresponding .c file and delete them later, but it would make the file rather big and I would like to use these tests again/modify them in the future as the project builds on itself.
I could also make a copy of the .h and include header guards, test it, then change it back before turning it in. I'm somewhat new to C and was curious if there was a simpler solution or a more efficient way of doing this without modifying the .h file. Thanks.
You can either wrap it with a second header guarded_header.h that has the guards:
#ifndef GUARDED_HEADER_H
#define GUARDED_HEADER_H
#include "unguarded_header.h"
#endif
Then in your source:
#include "guarded_header.h"
or you could just inline the above around each point of inclusion. I like the wrapping better, but if the original header already is known to define one or more macros, you can do it inline easily as:
#ifndef SOMETHING_UNGUARDED_HEADER_DEFINES
#include "unguarded_header.h"
#endif

include <stdbool.h> in both the header and the source?

I am still new to C. I have a question regarding source and header files. I have a header file like this:
#ifndef MISC_H_
#define MISC_H_
#define BYTE 8
#include <stdbool.h>
#include <stdio.h>
#include "DataStruct.h"
bool S_areEqual(char *firstString, char *secondString); /* (1) */
bool S_randomDataStructureCheck(char *string, DataStruct *data); /* (2) */
#endif
bool is used in the function parameters, and thus, I have it in the source as well. Do I have to #include <stdbool.h> in both the header file and the source file? Are there circumstances where I would and where I wouldn't?
What if I had a typedef in another header file that was used in the header as a function parameter? Do I have to #include "DataStruct.h" in both the header file and the source file?
What is the standard?
No you don't have to include in both header and source (.c) file. If you have included in a header that is included by the source then it will be available to the source as well. The order of header inclusion can be important when some headers depend on others. See this answer for more detail.
As an aside, you will notice the lines
#ifndef MISC_H_
#define MISC_H_
That ensures that the header is only included once.
Update
From the comments:
so in the source, you just include its respective header?
If you mean, should a source file only include its respective header, then it depends. Generally, files should include the files that they need.
If a source file needs a header, but that header is not needed by its own header file, then the include should go in the source rather than its header. One reason is that it is just conceptually cleaner that each file includes only the files that it needs, so it is easy to tell what the dependencies are. The other reason is that it reduces the impacts of change.
Lets look at an example. Say you have foo.c and foo.h and foo.c needs foodep.h to compile, but foo.h doesn't:
Option 1: foo.h
#include "foodep.h"
Now imagine that there are a number of other files foo1.h, foo2.h, foo3.h, etc that include foo.h. Then, any change to foodep.h affects all of those other files and their dependent header and source files.
Option 2: foo.c
#include "foodep.h"
Now, no other files have visibility of foodep.h. A change to foodep.h only impacts foo.c.
Generally, try to apply the same practices as you do with Object Oriented programming - encapsulate and minimize the scope of change.
The simple way to view this is that you should always include the headers which provide functions/aliases/macros you are using in your program, whether they actually need to be included should be left to compiler.
This is because every header is defined under #ifdef - #endif clause conditioned on some header-specific MACRO (And it is necessary to do this if you define your own header, to avoid multiple inclusions and thus avoid painful compiler errors).
Thus, my advice, if you are using bool in your program, you should include stdbool.h. If the compiler has already included it in definition of some other header, it will not include stdbool again.

Purpose of include guards in .c file

I have been seeing code like this usually in the start of source files in C
#ifndef _INCLUDE_GUARDS_C
#define _INCLUDE_GUARDS_C
main()
{
}
function1()
{
}
#endif
function2()
{
}
I am confused about the purpose of this ..?
I am aware if the include guards define in header files, but
what is the purpose of these include guards in source files ? and
why function2() is defined outside the include guards ?
There is no benefit to putting include guards in a C or C++ non-header source file.
I have implemented a preprocessor from scratch and studied include guards about as much as a person can, and that is totally pointless.
As for the function outside the guards, it looks like sloppiness to me. Or, sometimes when someone has a magic incantation, they aren't sure when it is supposed to apply, so they apply it randomly.
Old question, but...
I think it could be used when testing the code. When testing you need access to local functions that are not defined in the header, so you include the .c file... Yes, it's ugly. Yes, you have better options!
For the functions that are not defined in the header you don't need the include guard.

Best practice for using includes in C

I am learning C and I am unsure where to include files. Basically I can do this in .c or in .h files:
Option 1
test.h
int my_func(char **var);
test.c
#include <stdio.h>
#include "test.h"
int my_func(char **var) {printf("%s\n", "foo");}
int main() {...}
Option 2
test.h
#include <stdio.h>
int my_func(char **var);
test.c
#include "test.h"
int my_func(char **var) {printf("%s\n", "foo");}
int main() {...}
With option 2 I would only need to include test.h in whatever .c file I need the library. Most of the examples I see use option 1.
Are there some general rules when to do what or is this a question of personal preferences?
Don't use includes, you don't need.
I'd choose something like "Option 1". Why "something like" ? Because I'd create a separate file for the main and I'd keep all declaraions inside the .h and all definitions inside the corresponding .c.
Of course, both options are valid.
If you want to include only one header in your main, you can just create a header file, containing only includes - that's a common practice. This way, you can include only one header, instead of several.
I tend to prefer Option 1, as cyclic dependencies will come and bite you very quickly in option 2, and reducing the input size is the best way to guarantee faster compile times. Option 2 tends towards including everything everywhere, whether you really need it or not.
That said, it might be best to experiment a little with what works for structuring your projects. Hard and fast rules tend to not apply universally to these kinds of questions.
both options are correct. the C standard allows both solutions
All C standard headers must be made such that they can be included several times and in any order:
Standard headers may be included in any order; each may be included
more than once in a given scope, with no effect different from being
included only once
(From Preprocessor #ifndef)
I don't think that there is a universal rule (from a "grammatical" point of view, both your options are correct and will work). What is often done is to include in the .h file the headers you need for the library (as in your option 1), either because you'll need them when working with the library (thus avoiding always including the same set of header files in your .c files, which is more error prone), or because they are mentioned in the .h file itself (e.g., if you use a int32_t as type in the function prototypes of the .h files, you will of course need to include <stdint.h> in the .h file).
I prefer to use includes in c file.
If your program is getting bigger you might forgot to include something in one header file, but it is included in one other you use.
By including them in c-file you won't lose includes, while editing other files.
I prefer Option 1. I want to know what I used in my project, and in much time, Option 1 works more effective than Option 2 in time and efficiency.
There is no rule specifying you have following a particular fashion. Even if you include / not include in test.c file, it is not going to bother much, provided you include it in test.h file and include that test.h file in test.c. Hope you are clear with that.
This is because, you have preprocessor directives like #ifndef, #define, #endif. They are called Include guards. These are used in the inbuild header files. However, when you include a file written by you, either go with your option 2, or use include guards to be safe.
The include guards work as follows.
#ifndef ANYTHING
#define ANYTHING
..
..
..
#endif
So when you include for the first time, ANYTHING is not yet defined. So ifndef returns true, then ANYTHING gets defined, and so...on.. But the next time if you include the same file ( by mistake) ifndef would return a false since ANYTHING is now defined and so the file would not be included at all. This protection is necessary to avoid duplicate declarations of variable present in the header file. That would give you a compilation error.
Hope that helps
Cheers

How to structure #includes in C

Say I have a C program which is broken to a set of *.c and *.h files. If code from one file uses functions from another file, where should I include the header file? Inside the *.c file that used the function, or inside the header of that file?
E.g. file foo.c includes foo.h, which contains all declarations for foo.c; same for bar.c and bar.h. Function foo1() inside foo.c calls bar1(), which is declared in bar.h and defined in bar.c. Now the question is, should I include bar.h inside foo.h, or inside foo.c?
What would be a good set of rules-of-thumb for such issues?
You should include foo.h inside foo.c. This way other c files that include foo.h won't carry bar.h unnecessarily. This is my advice for including header files:
Add include definitions in the c files - this way the file dependencies are more obvious when reading the code.
Split the foo.h in two separate files, say foo_int.h and foo.h. The first one carries the type and forward declarations needed only by foo.c. The foo.h includes the functions and types needed by external modules. This is something like the private and public section of foo.
Avoid cross references, i.e. foo references bar and bar references foo. This may cause linking problems and is also a sign of bad design
As others have noted, a header foo.h should declare the information necessary to be able to use the facilities provided by a source file foo.c. This would include the types, enumerations and functions provided by foo.c. (You don't use global variables, do you? If you do, then those are declared in foo.h too.)
The header foo.h should be self-contained and idempotent. Self-contained means that any user can include foo.h and not need to worry about which other headers may be needed (because foo.h includes those headers). Idempotent means that if the header is included more than once, there is no damage done. That is achieved by the classic technique:
#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED
...rest of the contents of foo.h...
#endif /* FOO_H_INCLUDED */
The question asked:
File foo.c includes foo.h, which contains all declarations for foo.c; same for bar.c and bar.h. Function foo1() inside foo.c calls bar1(), which is declared in bar.h and defined in bar.c. Now the question is, should I include bar.h inside foo.h, or inside foo.c?
It will depend on whether the services provided by foo.h depend on bar.h or not. If other files using foo.h will need one of the types or enumerations defined by bar.h in order to use the functionality of foo.h, then foo.h should ensure that bar.h is included (by including it). However, if the services of bar.h are only used in foo.c and are not needed by those who use foo.h, then foo.h should not include bar.h
I would only include header files in a *.h file that required for the header file itself. Header files that are needed for a source file, in my opinion, should be included in the source file so that the dependencies are obvious from the source. Header files should be be built to handle multiple inclusion so you could put it in both if required for clarity.
Using the examples of foo.c and foo.h I've found these guidelines helpful:
Remember that the purpose of foo.h is to facilitate the use of foo.c, so keep it as simple, organized, and self-explanatory as possible. Be liberal with comments that explain how and when to use the features of foo.c -- and when not to use them.
foo.h declares the public features of foo.c: functions, macros, typedefs, and (shudder) global variables.
foo.c should #include "foo.h -- see discussion, and also Jonathan Leffler's comment below.
If foo.c requires additional headers for it to compile, include them in foo.c.
If external headers are required for foo.h to compile, include them in foo.h
Leverage the preprocessor to prevent foo.h from being included more than once. (See below.)
If for some reason an external header will be required in order for another .c file to use the features in foo.c, include the header in foo.h to save the next developer from unnecessary debugging. If you're averse to this, consider adding macro that will display instructions at compile-time if the required headers haven't been included.
Don't include a .c file within another .c file unless you have a very good reason and document it clearly.
As kgiannakakis noted, it's helpful to separate the public interface from the definitions and declarations needed only within foo.c itself. But rather than creating two files, it's sometimes better to let the preprocessor do this for you:
// foo.c
#define _foo_c_ // Tell foo.h it's being included from foo.c
#include "foo.h"
. . .
// foo.h
#if !defined(_foo_h_) // Prevent multiple inclusion
#define _foo_h_
// This section is used only internally to foo.c
#ifdef _foo_c_
. . .
#endif
// Public interface continues to end of file.
#endif // _foo_h_ // Last-ish line in foo.h
I include the most minimal set of headers possible in the .h file, and include the rest in the .c file. This has the benefit of sometimes reducing compilation times. Given your example, if foo.h doesn't really need bar.h but includes it anyway, and some other file includes foo.h, then that file will be recompiled if bar.h changes, even though it may not actually need or use bar.h.
The .h file should define the public interface (aka the api) to the functions in the .c file.
If the interface of file1 uses the interface of file2 then #include file2.h in file1.h
If the implementation in file1.c makes use of stuff in file2.c then file1.c should #include file2.h.
I must admit though that - because I always #include file1.h in file1.c - I normally wouldn't bother #including file2.h directly in file1.c if it was already #included in file1.h
If you ever find yourself in the situation where two .c files #include each others .h files then it is a sign that modularity has broken down and you ought to think about restructuring things a bit.

Resources