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.
Related
I have a header-only library, lets call it foo.h, which is included into a bar.h, which is furthermore included into a foobar.h. The linker throws a LNK2005 error saying that the functions and structs from foo.h are already defined inside the foobar.obj.
The foo.h file looks something like this:
#pragma once
#ifndef FOO
#define FOO
//few structs and functions declarations and definitions (these aren't static nor inline) inside a namespace
#endif
//include guards added after I got the error for the first time
The bar.h looks like this:
#include "foo.h"
//some other code
The foobar.h looks like this:
#include "bar.h"
//some other code
This question is probably duplicit of this: Why aren't include guards or pragma once working?
But, is there another way to fix this than making these functions inline or static? Maybe without editing the foo.h at all?
Most likely bar.h or foobar.h are included in several files.
The best solution to this is to declare all functions/methods in your file as inline. You could also declare them static (or, in case of C++, put them into anonymous namespace) but that's less efficient because code will be duplicated.
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
Suppose I have a library foo which consists of the modules foo and util and has the following source tree:
foo/
foo.c
foo.h
util.c
util.h
The public API of the library is defined in foo.h and all global identifiers are properly prefixed with foo_ or util_. The module util is only used by foo. To prevent name clashes with other modules named util I want to create a (static) library in which only identifiers from module foo are visible. How can I do this?
Edit: I have searched the internet quite extensively but surprisingly this seems to be one of those unsolved problems in computer science.
There are probably other possible approaches, but here's one:
You might consider including the file util.c within foo.c and making all the util functions / globals static. i.e.:
#include "util.c"
// ...
This works the same as *.h files, it simply ports the whole source into foo.c, nesting util.c and making all the static data available.
When I do this, I rename the file to .inc (i.e. util.c => util.inc)...
#include "util.inc"
// ...
...it's an older convention I picked up somewhere, though it might conflict with assembler files, so you'll have to use your own discretion.
EDIT
Another approach might require linker specific directives. For example, this SO answer details GNU's ld to achieve this goal. There are other approaches as well, listed in that same thread.
The following is GCC-specific.
You can mark each utility function with
__attribute__((visibility ("hidden")))
which will prevent it from being linked to from another shared object.
You can apply this to a series of declarations by surrounding them with
#pragma GCC visibility push(hidden)
/* ... */
#pragma GCC visibility pop
or use -fvisibility=hidden when compiling the object, which applies to declarations without an explicit visibility (e.g. neither __attribute__((visibility)) nor #pragma GCC visibility).
Before each variable and function declaration in util.h, define a macro constant which renames the declared identifier by adding the library prefix foo_, for instance
#define util_x foo_util_x
extern int util_x;
#define util_f foo_util_f
void util_f(void);
...
With these definitions in place, no other parts of the code need to be changed, and all global symbols in the object file util.o will be prefixed with foo_. This means that name collisions are less likely to occur.
Say I have two header and implementation files, A and B.
B:
#include "B.h"
void funcFromB(); //prototype
...
void funcFromB()
{
...
}
A:
#include "B.h"
void funcFromB(); //prototype
...
funcFromB(); //will this work correctly?
Will calling funcFromB() from A work correctly if the function is not defined in header of B (B.h)?
Yes, the function will work correctly, provided B.o is linked to A. The .h files and .c files have nothing inherently to do with each other. For clarity purposes, they SHOULD, but nothing forces them to do so. There is no requirement for .h files at all, but coders find them useful to organize information and avoid repeating oneself.
The code fragment in your question both compiles ("works") and smells
The question is clearly a bit in the grey area, but here's my interpretation of it and the solution.
This is your B.h
void funcFromB();
i.e. you have the function signature in the header file.
I am not sure what exactly your A.h file has, but I assume it is not really important for our discussion, so we will leave it to that.
Now your B.c file will contains the implementation of the method funcFromB(). In that case, you don't have to do
void funcFromB(); //prototype
The above line is not required. When you #include your header file, the method signature will be available. So this is how your B.c file will look like.
#include "B.h"
void funcFromB()
{
...
}
Now, for you to be able to use this function in A.c, all you need to do is
#include "B.h"
funcFromB(); //This will work correctly
Here, the function will get the signature of the function from B.h, and the implementation is will get from B.c at compile time. All you need to do is, just call the function.
Now, coming to what have we done here. Well, what we wanted to do was to organise our code in a better way. For that, we wanted to use a function, defined in a different file and use it in another file. Now, B.c contains the definition of the function. B.h contains the method signature. If you want to use the function in A.c, you just need to tell this compilation unit, that how does the function look like. And when you link the files together later during compile time, the method implementation will be found out by the compiler on it's own.
Cheers.
It will work,given you define your funFromB() function, preferably in the B.c file; In that case, just #include the B.h file containing the funcFromB() prototype for the preprocessor in your A.c and B.c(this is the one where you will be defining the function) files , and you should be good to go. No need to re-define the function in A.c, nor re-declare the prototype in (any) .c file, as long as it is declared in the b.h file, and every .c file using the function includes the corresponding (B).h file.
PS: Using headers is a great way of improving readability, so I wouldn't skip that part, by declaring the prototype in the .c file. If you want to avoid Headers, you could still just use one single file, let's call it 'master.h', where you would declare ALL the prototypes used by ALL .c files, and include the master.h in all your.c files.
Headers tend to help keeping a better overview of how your files are linked to another, and establish the proper dependencies
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.