Tips on using preprocessor #ifndef - c

I'm learning C and hope someone can explain what's the logic of using #ifndef?
I also find many C programs I looked, people seems following a convention using the filename following the #ifndef, #define and #endif. Is there any rule or tip on how to choose this name?
#ifndef BITSTREAM_H
#define BITSTREAM_H
#include <stdio.h>
#include <stdint.h>
/*Some functions*/
#endif

Header files will often use logic like this to avoid being included
more than once. The first time a source file includes them, the name
isn't defined, so it gets defined and other things are done.
Subsequent times, the name is defined, so all that is skipped.

The one you posted, in particular, is called an Include Guard.

The term for what you're looking for is Preprocessor Directives.
#ifndef doesn't need to be followed by a filename, for example it's common to see #ifdef WINDOWS or #ifndef WINDOWS, etc.

#ifndef means "if not defined". It is commonly used to avoid multiple include's of a file.

Tom Zych: "Header files will often use logic like this to avoid being included more than once."
This is true but it really is only necessary for "public" headers, like headers for library functions, where you don't have any control over how the headers are included.
This trick is unnecessary for headers used in projects where you have control over how things are included. (If there's a use for them outside of public headers, it's not a common one).
If you avoid using them in "private" headers, you'll more likely include headers in a less haphazard way.

Related

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 copy macro contents to another macro in C [duplicate]

I am using both the JUCE Library and a number of Boost headers in my code. Juce defines "T" as a macro (groan), and Boost often uses "T" in it's template definitions. The result is that if you somehow include the JUCE headers before the Boost headers the preprocessor expands the JUCE macro in the Boost code, and then the compiler gets hopelessly lost.
Keeping my includes in the right order isn't hard most of the time, but it can get tricky when you have a JUCE class that includes some other classes and somewhere up the chain one file includes Boost, and if any of the files before it needed a JUCE include you're in trouble.
My initial hope at fixing this was to
#undef T
before any includes for Boost. But the problem is, if I don't re-define it, then other code gets confused that "T" is not declared.
I then thought that maybe I could do some circular #define trickery like so:
// some includes up here
#define ___T___ T
#undef T
// include boost headers here
#define T ___T___
#undef ___T___
Ugly, but I thought it may work.
Sadly no. I get errors in places using "T" as a macro that
'___T___' was not declared in this scope.
Is there a way to make these two libraries work reliably together?
As greyfade pointed out, your ___T___ trick doesn't work because the preprocessor is a pretty simple creature. An alternative approach is to use pragma directives:
// juice includes here
#pragma push_macro("T")
#undef T
// include boost headers here
#pragma pop_macro("T")
That should work in MSVC++ and GCC has added support for pop_macro and push_macro for compatibility with it. Technically it is implementation-dependent though, but I don't think there's a standard way of temporarily suppressing the definition.
Can you wrap the offending library in another include and trap the #define T inside?
eg:
JUICE_wrapper.h:
#include "juice.h"
#undef T
main.cpp:
#include "JUICE_wrapper.h"
#include "boost.h"
rest of code....
I then thought that maybe I could do some circular #define trickery like so:
The C Preprocessor doesn't work this way. Preprocessor symbols aren't defined in the same sense that a symbol is given meaning when, e.g., you define a function.
It might help to think of the preprocessor as a text-replace engine. When a symbol is defined, it's treated as a straight-up text-replace until the end of the file or until it's undefined. Its value is not stored anywhere, and so, can't be copied. Therefore, the only way to restore the definition of T after you've #undefed it is to completely reproduce its value in a new #define later in your code.
The best you can do is to simply not use Boost or petition the developers of JUCE to not use T as a macro. (Or, worst case, fix it yourself by changing the name of the macro.)

#include inside the main () function

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.

best-practice on C header files with #ifndef #define #endif

what is concerned best practice regarding the following "pattern"?
#ifndef BLAFOO_H
#define BLAFOO_H
/* ...
* ...
*/
#endif /* BLAFOO_H */
how should i name the header in the #define directive? i've seen all from said BLAFOO_H to __BLAFOO_H to _BLAFOO_H_ etc..
Name them BLAFOO_H (personnally I use BLAFOO_H_ where BLAFOO is the header file name ).
Make sure your BLAFOO doesn't clash with other files/libraries/etc. you're using, e.g. have your project and/or module name be parth of that name.
Identifiers starting with a _ is reserved for the implementation/compiler, so don't use that.
I use an UUID that is my guarantee that #define not clashed with others. I've seen it somewhere and decided to use it as well.
My pattern is like this: __<filename>_H_<uuid>__,
eg. #define __TYPES_H_79057761_16D6_478A_BFBC_BBF17BD3E9B9__ for a file named types.h
As with other C-style questions, just be consistent. There is no way that you are going to know the namespace every library that someone might link with your program in the future. Why? Many of them have not been written yet :)
As such, its not a question of include guards, its a question of what to name the header in the first place.
I might come up with some cool new string utilities, and name the header strutil. That's a bad idea, because (surely) someone else has come up with cool new string utilities and named the header the same.
So, I name mine post_strutils.h and:
#ifndef POST_STRUTILS_H
#define POST_STRUTILS_H
/* code */
#endif
I may even call it post_str_utils.h and define the include guards appropriately because I know that I have a very common last name. Finding a namespace is sometimes difficult. Simply using one offers no guarantee that someone else did a search prior to releasing something to the wild. Be as unique as possible.
Depending on where someone tells their compiler to search for headers, its not just namespace conflicts that come into play, its also file names. Do your best to name the header uniquely, then write the include guard to match it. Someone might want to #error if the header has been included multiple times, if only to cut #include directives that aren't needed, using a UUID kind of makes doing so confusing, since it doesn't match (or even resemble) the file name of the header in question. It also makes grep/awk(or similar) powered lint scripts harder to write.
I'm not saying you should name every library / module after yourself, but do take care to make the public header file names unique. A quick conference with a search engine will tell you if you hit on an unused namespace. Please, let the include guards match (or at least closely resemble) the header. Again, consistency is highly praised. From your example, I'd expect:
int blahfoo_init(void);
double blahfoo_getval(blahfoo_t *blah);
If you go through the bother of finding a unique namespace, be sure to use it :)
The only real requirement is that it won't conflict with another project that uses the same name for its file. For all of the projects I've seen, it usually completely quantifies the namespace (or whatever folder the file is in for C) along with the project name. Sometimes it includes the date the file was created too.
So if you're working on project ABC in folder DEF today, then you could do:
#ifndef ABC_DEF_BLAFOO_H_05_30_2010
And this is very unlikely to conflict with anything.
It doesn't really matter as long as it's not likely to be used anywhere else. I usually go with something like BLAFOO_H_INCLUDED.

#include <> files in different files

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

Resources