In C, we can include a file as #include "filename.h"
But for instance if the filename.h has the contents as -
#ifndef FILE_NAME_GUARD
#define FILE_NAME_GUARD
//contents
.
.
.
In my another file, can I include the above file as #include <FILE_NAME_GUARD> instead of #include "filename.h"?
I tried this way and I was surprised to see that there was no compiler error or linker error. But there was this warning:
FILE_NAME_GUARD: No such file or directory
Please help in clarifying whether can we include a header with its multiple_header_guard name instead of the filename?
No - not unless the name you use for the guard macro precisely matches the file name. For example, you can include a file like this:
#define filename <stdio.h>
#include filename
The filename will be macro-replaced, so the result be equivalent to:
#include <stdio.h>
So, if you used a header-guard macro that precisely matched the name of the file to include (including quotes or angle brackets), you could make it work -- but otherwise it'll fail. I don't think it would be a good idea to write code this way. In most cases, it seems to make no sense at all -- the header guard macro will only be defined when that header has already been included, which is exactly the case where you don't (usually) want to include it.
Actually, what goes on between the <> or "" in an include statement is pretty much totally implementation defined so you can't say for certain.
Technically an implementation could remember which include file mapped to which guard name and intelligently handle that, but I've never seen that in the wild.
And, judging by your warning message, your implementation doesn't do it either.
Please help in clarifying whether can we include the a header with its multiple_header_guard name instead of the filename??
No, you can't, because the preprocessor ain't magic.
You can't really include a file by its header guard macro. Normally, the header guard macro is defined as an empty string, and it's hard to include a file named by the empty string.
You can write:
#define MAGIC_HEADER "magic.h"
#include MAGIC_HEADER
where the macro used after the #include matches one of the forms "name" or <name>. However, there'd be no point in trying that with header guards. By the time the header guard macro is defined, you've already included the file and won't want to do so again (with a nod at <assert.h> which can be included multiple times with a different effect each time, depending on whether the NDEBUG macro is defined or not).
Related
Assuming we have 2 files DIO.c and DIO.h. I used to #include all necessary header files in DIO.h and only #include DIO.h in DIO.c. while working on drivers for ATmega32, I found out that some functions are declared implicitly while including other modules. This made me wonder is that right to include all files in header file instead of source file? and how what
i'm doing currently affects dependency?
After visiting some repos on github i found out that they never #include anything in header files, and only include everything in C file, which made me more confused about what about typedefs? how they use them without including the header file containing them?
Here is an example of DIO.h file:
#include "Dio_Private.h"
#include "Dio_Config.h"
#include "../../Utilities/Macros.h"
and here is an example of DIO.c file:
#include "DIO.h"
If the answer was that I should include all header files in C file, what about enums?
for example, if I want to use enums defined in DIO.h file in any other module, should I now seperate these enums in another header file and only #include it?
Thanks in advance :)
It's perfectly fine to #include multiple headers in one and use that (provided you use proper include guards).
Having said that, if you don't like typing multiple #includes over and over and you are thinking of creating a big one just for convenience, keep in mind that this will affect compilation time (since the contents of all the headers have to be parsed for every .c file that includes them).
#ShaneGervais is right that you should use include guards, and right that #include is somewhat like pasting the contents of the header file into your source file, but incorrect about the rest of it.
Example Dio_Private.h
#ifndef DIO_PRIVATE_H_
#define DIO_PRIVATE_H_
int dinput(char **);
int doutput(char *);
#endif
This will ensure no errors on multiple #include
Do not use #pragma once. Do not use #define __DIO_PRIVATE_H__. These are not standard C and the latter one results in undefined behavior.
Do not define your functions in a header file, especially as a beginner. For very small, very succinct functions that do not use global variables and which will not bloat your code too much if used several times over, it may be appropriate, when you more fully understand how to use them, to define them in a header file. Example:
#ifndef MYSTRDUP_H_
#define MYSTRDUP_H_
#include <stdlib.h>
#include <string.h>
static inline char *mystrdup(const char *s) {
size_t n = strlen(s) + 1;
char *r = malloc(n);
if (r) memcpy(r, s, n);
return r;
}
#endif
This question is a matter of opinion and style, and therefore probably not regarded as a "good" question for SO. I can offer advice only:
Include anything in the header file necessary to make the header file valid without requiring additional includes.
So for example if header file xxx.h references a symbol such as int32_t, then it should explicitly include stdint.h. Otherwise the user of the header file will have to "know" that stdint.h is required to be included before xxx.h, even if the subsequent source never references stdint.h type or symbols.
To not allow nested includes is a nonsense, because the user of a header file will have to know or work out what include dependencies are required and they cold be very many.
On the other hand to include headers for symbols not referenced in the header itself pulls in interfaces the user might not expect and is inefficient. You might do that when a public interface is a collation or parts in multiple headers, but you need ot be able to justify it and follow the principles of maximum cohesion, minimal coupling.
After visiting some repos on github ...
I would not assume some randomly selected repo to be definitive or even good practice or the arbiter of such. Being published on Github is not an indication of quality - it is a poor strategy to learning good coding style. You might better take your "best-practice" cues from standard or device library headers for example.
I amcoming from a python background, where the following is valid:
def f():
import someLibrary
someLibrary.libraryFunction()
So when I needed to debug C code, I wrote, in the middle of my function:
void f(int param)
{
int status;
/* other code */
#include <stdio.h>
printf("status: %d", status);
/* more code */
}
And it compiled and worked as I expected. Later it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include~ statement with the contents ofstdio.h`.
So why was this valid code?
it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include statement with the contents ofstdio.h.
The logic on that doesn't make sense. Just because the pre-processor inserts the text from the stdio.h file doesn't mean it should not compile. If there's nothing in that file that would result in a compile error, then it will compile just fine.
Furthermore, headers usually have a multiple inclusion guard in them. So if they were included already previously, any further attempts to include it have no effect. In this case, if <stdio.h> was already included previously in the file (directly or indirectly), the #include will have no effect.
With that being said, don't do that though. In C, standard headers are not supposed to be included while inside a function scope.
Yeah, C and Python are pretty different in this respect.
It is correct that the preprocessor replaces the #include directive with the contents of the included file prior to compilation.
Whether it leads to a compilation error or not depends entirely on the contents of the included file. Standard headers like stdio.h don't contain any executable statements - they only contain things like typdefs, function declarations, other macros, etc. They also usually have some kind of #include guards in place that prevent them from being loaded more than once per translation unit (that is, if you #include a file that includes stdio.h, and then #include <stdio.h> directly in the same source file, the contents of stdio.h will only be loaded once).
Theoretically, there's no problem with including stdio.h at random points in the code, but it can lead to problems. In this case all of stdio.h's contents will only be visible to the body of f - not a problem if only f needs to use anything in stdio.h, but otherwise it will lead to headaches.
Standard headers are best included at the beginning of the source file.
I would like to know if it's possible that inside the main() function from C to include something.
For instance, in a Cell program i define the parameters for cache-api.h that later in the main() function i want to change .
I understood that what was defined with #define can be undefined with #undef anywhere in the program, but after redefining my needed parameters I have to include cache-api.h again . Is that possible?
How can I solve this problem more elegant ? Supposing I want to read from the main storage with cache_rd(...) but the types would differ during the execution of a SPU, how can i use both #define CACHED_TYPE struct x and #define CACHED_TYPE struct y in the same program?
Thanks in advance for the answer, i hope i am clear in expression.
#define and #include are just textual operations that take place during the 'preprocessing' phase of compilation, which is technically an optional phase. So you can mix and match them in all sorts of ways and as long as your preprocessor syntax is correct it will work.
However if you do redefine macros with #undef your code will be hard to follow because the same text could have different meanings in different places in the code.
For custom types typedef is much preferred where possible because you can still benefit from the type checking mechanism of the compiler and it is less error-prone because it is much less likely than #define macros to have unexpected side-effects on surrounding code.
Yes, that's fine (may not be the clearest design decision) but a #include is just like a copy-and-paste of that file into the code right where the #include is.
#define and #include are pre-processor macros: http://en.wikipedia.org/wiki/C_preprocessor
They are converted / inlined before compilation.
To answer your question ... no, you really wouldn't want do do that, at least for the sake of the next guy that has to try and unscramble that mess.
You can #include any file in any file. Whether it is then valid depends on the content of the file; specifically whether that content would be valid if it were entered directly as text.
Header files generally contain declarations and constructs that are normally only valid outside of a function definition (or outside any kind of encoding construct) - the clue is in the name header file. Otherwise you may change the scope of the declarations, or more likley render the compilation unit syntactically invalid.
An include file written specially for the purpose may be fine, but not just any arbitrary header file.
General purpose header files should have include guards to prevent multiple declaration, so unless you undefine the guard macro, re-including a header file will have no effect in any case.
One possible solution to your problem is to create separately compiled modules (compilation units) containing wrapper functions to the API you need to call. Each compilation unit can then include the API header file after defining the appropriate configuration macros. You will then have two separate and independent interfaces provided by these wrapper functions.
In C (or a language based on C), one can happily use this statement:
#include "hello.h";
And voila, every function and variable in hello.h is automagically usable.
But what does it actually do? I looked through compiler docs and tutorials and spent some time searching online, but the only impression I could form about the magical #include command is that it "copy pastes" the contents of hello.h instead of that line. There's gotta be more than that.
Logically, that copy/paste is exactly what happens. I'm afraid there isn't any more to it. You don't need the ;, though.
Your specific example is covered by the spec, section 6.10.2 Source file inclusion, paragraph 3:
A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.
That (copy/paste) is exactly what #include "header.h" does.
Note that it will be different for #include <header.h> or when the compiler can't find the file "header.h" and it tries to #include <header.h> instead.
Not really, no. The compiler saves the original file descriptor on a stack and opens the #included file; when it reaches the end of that file, it closes it and pops back to the original file descriptor. That way, it can nest #included files almost arbitrarily.
The # include statement "grabs the attention" of the pre-processor (the process that occurs before your program is actually compiled) and "tells" the pre-processor to include whatever follows the # include statement.
While the pre-processor can be told to do quite a bit, in this instance it's being asked to recognize a header file (which is denoted with a .h following the name of that header, indicating that it's a header).
Now, a header is a file containing C declarations and definitions of functions not explicitly defined in your code. What does this mean? Well, if you want to use a function or define a special type of variable, and you know that these functions/definition are defined elsewhere (say, the standard library), you can just include (# include) the header that you know contains what you need. Otherwise, every time you wanted to use a print function (like in your case), you'd have to recreate the print function.
If its not explicitly defined in your code and you don't #include the header file with the function you're using, your compiler will complain saying something like: "Hey! I don't see where this function is defined, so I don't know what to with this undefined function in your code!".
It's part of the preprocessor. Have a look at http://en.wikipedia.org/wiki/C_preprocessor#Including_files. And yes, it's just copy and paste.
This is a nice link to answer this question.
http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Usually #include and #include "path-name" just differs in the order of the search of the pre processor
If I have a several header files :lets say 1.h, 2.h, 3.h.
Let's say the all three of the header files have #include <stdlib.h> and one of the include files in them.
When I have to use all 3 header files in a C file main.c,
it will have 3 copies of #include <stdlib.h> after the preprocessor.
How does the compiler handle this kind of conflict?
Is this an error or does this create any overhead?
If there are no header guards, what will happen?
Most C headers include are wrapped as follows:
#ifndef FOO_H
#define FOO_H
/* Header contents here */
#endif
The first time the preprocessor scans this, it will include the contents of the header because FOO_H is undefined; however, it also defines FOO_H preventing the header contents from being added a second time.
There is a small performance impact of having a header included multiple times: the preprocessor has to go to disk and read the header each time. This can be mitigated by adding guards in your C file to include:
#ifndef FOO_H
#include <foo.h>
#endif
This stuff is discussed in great detail in Large-Scale C++ Software Design (an excellent book).
This is usually solved with preprocessor statements:
#ifndef __STDLIB_H
#include <stdlib.h>
#define __STDLIB_H
#endif
Although I never saw it for common header files like stdlib.h, so it might just be necessary for your own header files.
The preprocessor will include all three copies, but header guards will prevent all but the first copy from being parsed.
Header guards will tell the preprocessor to convert subsequent copies of that header file to effectively nothing.
Response to edit:
Standard library headers will have the header guards. It would be very unusual and incorrect for them to not have the guards.
Similarly, it is your responsibility to use header guards on your own headers.
If header guards are missing, hypothetically, you will get a variety of errors relating to duplicate definitions.
Another point: You can redeclare a function (or extern variable) a bazillion times and the compiler will accept it:
int printf(const char*, ...);
int printf(const char*, ...);
is perfectly legal and has a small compilation overhead but no runtime overhead.
That's what happens when an unguarded include file is included more than once.
Note that it is not true for everything in an include file. You can't redeclare an enum, for example.
This is done by one of the two popular techniques, both of which are under stdlib's responsibility.
One is defining a unique constant and checking for it, to #ifdef out all the contents of the file if it is already defined.
Another is microsoft-specific #pragma once, that has an advantage of not having to even read the from the hard drive if it was already included (by remembering the exact path)
You must also do the same in all header files you produce. Or, headers that include yours will have a problem.
As far a I know regular include simply throws in the contents of another file. The standard library stdlib.h urely utilizes the code guards: http://en.wikipedia.org/wiki/Include_guard, so you end up including only one copy. However, you can break it (do try it!) if you do: #include A, #undef A_GUARD, #include A again.
Now ... why do you include a .h inside another .h? This can be ok, at least in C++, but it is best avoided. You can use forward declarations for that: http://en.wikipedia.org/wiki/Forward_declaration
Using those works for as long as your code does not need to know the size of an imported structure right in the header. You might want to turn some function arguments by value into the ones by reference / pointer to solve this issue.
Also, always utilize the include guards or #pragma once for your own header files!
As others have said, for standard library headers, the system must ensure that the effect of a header being included more than once is the same as the header being included once (they must be idempotent). An exception to that rule is assert.h, the effect of which can change depending upon whether NDEBUG is defined or not. To quote the C standard:
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, except that the
effect of including <assert.h> depends on the definition of NDEBUG.
How this is done depends upon the compiler/library. A compiler system may know the names of all the standard headers, and thus not process them a second time (except assert.h as mentioned above). Or, a standard header may include compiler-specific magic (mostly #pragma statements), or "include guards".
But the effect of including any other header more than once need not be same, and then it is up to the header-writer to make sure there is no conflict.
For example, given a header:
int a;
including it twice will result in two definitions of a. This is a Bad Thing.
The easiest way to avoid conflict like this is to use include guards as defined above:
#ifndef H_HEADER_NAME_
#define H_HEADER_NAME_
/* header contents */
#endif
This works for all the compilers, and doesn't rely of compiler-specific #pragmas. (Even with the above, it is a bad idea to define variables in a header file.)
Of course, in your code, you should ensure that the macro name for include guard satisfies this:
It doesn't start with E followed by an uppercase character,
It doesn't start with PRI followed by a lowercase character or X,
It doesn't start with LC_ followed by an uppercase character,
It doesn't start with SIG/SIG_ followed by an uppercase character,
..etc. (That is why I prefer the form H_NAME_.)
As a perverse example, if you want your users guessing about certain buffer sizes, you can have a header like this (warning: don't do this, it's supposed to be a joke).
#ifndef SZ
#define SZ 1024
#else
#if SZ == 1024
#undef SZ
#define SZ 128
#else
#error "You can include me no more than two times!"
#endif
#endif