Testing some code including term.h, I've seen some strange errors using usual identifiers such as tab or columns. It comes from the fact that this header defines a lot of macros. Here are some examples:
/* from term.h */
#define columns CUR Numbers[0]
#define lines CUR Numbers[2]
#define bell CUR Strings[1]
#define insert_line CUR Strings[53]
#define tab CUR Strings[134]
However, I didn't find any documentation about these macroconstants. It seems to be shortcuts to access to some members of a TERMINAL data structure. Of course, a solution is to #undef every identifier used in the source code. But it is very restrictive.
So my question is: why do not prefix the identifiers of term.h?
They are often used as local variables in real source code, so it leads to incomprehensible errors.
There are two ways to deal with the identifier clash:
Change the identifiers in term.h
Change the identifiers in your code
The first is a no-no for reasons I hopefully need not explain. term.h was there long before your code ever formed as a thought in your brain. Thus it is entirely your fault^Wproblem^Wresponsibility to have created clashing identifiers. :-)
Maybe there's another option:
Don't use/include term.h in the first place.
One option, assuming you MUST use term.h is to isolate the inclusion of that file to a particular module, so that your overall code doesn't clash. But as Jens says, it's your task to "not have name clashes". Public header files that belong to the system shouldn't be changed just because you use the same names as those.
Related
I was reading the C Preprocessor guide page on gnu.org on computed includes which has the following explanation:
2.6 Computed Includes
Sometimes it is necessary to select one of several different header
files to be included into your program. They might specify
configuration parameters to be used on different sorts of operating
systems, for instance. You could do this with a series of
conditionals,
#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3 …
#endif
That rapidly becomes tedious. Instead, the preprocessor offers the
ability to use a macro for the header name. This is called a computed
include. Instead of writing a header name as the direct argument of
‘#include’, you simply put a macro name there instead:
#define SYSTEM_H "system_1.h"
…
#include SYSTEM_H
This doesn't make sense to me. The first code snippet allows for optionality based on which system type you encounter by using branching if elifs. The second seems to have no optionality as a macro is used to define a particular system type and then the macro is placed into the include statement without any code that would imply its definition can be changed. Yet, the text implies these are equivalent and that the second is a shorthand for the first. Can anyone explain how the optionality of the first code snippet exists in the second? I also don't know what code is implied to be contained in the "..." in the second code snippet.
There's some other places in the code or build system that define or don't define the macros that are being tested in the conditionals. What's suggested is that instead of those places defining lots of different SYSTEM_1, SYSTEM_2, etc. macros, they'll just define SYSTEM_H to the value that's desired.
Most likely this won't actually be in an explicit #define, instead of will be in a compiler option, e.g.
gcc -DSYSTEM_H='"system_1.h"' ...
And this will most likely actually come from a setting in a makefile or other configuration file.
This is the first time I ran into the "redefinition of macro" concept while reading the C book by Mike Banahan (Section 7.3.2). But from what I can gauge from the following paragraph given there, redefinition won't be of any use at all other than repeating the same thing, given the tight restrictions. Of course my understanding is wrong and the author must be having a point. So can you please explain in simple terms what exactly redefinition of a macro in C is, and what exactly can we do to redefine it after we comply with the restrictions and rules given for that. A sample code will be very helpful. Thank you.
Extracted text follows:
The Standard allows either type of macro to be redefined at any time,
using another # define, provided that there isn't any attempt to
change the type of the macro and that the tokens making up both the
original definition and the redefinition are identical in number,
ordering, spelling and use of white space. In this context all white
space is considered equal, so this would be correct:
#define XXX abc/*comment*/def hij
#define XXX abc def hij
because comment is a form of white space. The token sequence for both cases (w-s stands for a white-space token) is:
# w-s define w-s XXX w-s abc w-s def w-s hij w-s
In practice, you generally do not want to redefine macros. Most of the time it happens due to name collision (two pieces of code defining a macro with the same name that may or may not do the same thing). The rule you cite says redefinition is allowed in the case where the only difference between the two definitions is white space. In that case, both definitions will do the same thing. In any other case, all bets are off.
For example, a common thing to want is the maximum of two numbers. If you write a MAX macro, one way to do it would be:
// ASSUME: multiple references to macro parameters do not cause problems
#define MAX(a, b) ((a) > (b) ? (a) : (b))
Since MAX is the obvious name for a macro that returns the maximum of two numbers, there is a pretty good chance that someone else might have the same idea and also define a MAX macro. If they happen to define it exactly the same way you did, the compiler will accept the multiple definitions, because they do the same thing (though some compilers will still warn about it).
If someone defines MAX differently, the compiler will throw an error on the redefinition. Throwing an error is a good thing. Had the compiler always picked either the first or last definitions, the programmer would most likely not be aware that a different macro than they expected will be used.
If you need to work around multiple definitions of macros (e.g., two different 3rd party libraries choose the same name), you can use #ifdef to check if the macro is already defined and #undef to "undefine" the first definition if you would rather have the second. Such solutions are generally fragile. If you have a choice, avoiding name conflicts is a better solution.
My project incorporates a stack, which has a number of user-defined types (typedef). The problem is that many of these type definitions conflict with our in-house type definitions. That is, the same symbol name is being used. Is there any way to protect against this?
The root of the problem is that to use the stack in our application, or wrapper code, as the case may be, a certain header file must be included. This stack header file in turn includes the stack provider's types definition file. That's the problem. They should have included their type definition file via a non-public include path, but they didn't. Now, there are all sorts of user-defined type conflicts for very common names, such as BYTE, WORD, DWORD, and so forth.
Since you probably can't easily change the program stack you are using, you will have to start with your own code.
The first thing to do is (obviously) to limit the number of names in the global namespace, as far as possible. Don't use global variables, just use static ones, as an example.
The next step is to adopt a naming convention for your code modules. Suppose you have an "input module" in the project. You could then for example prefix all functions in the input module "inp".
void inp_init (void);
void inp_get (int input);
#define INP_SOMECONSTANT 4
typedef enum
{
INP_THIS,
INP_THAT,
} inp_something_t;
And so on. Whenever these items are used elsewhere in the code, they will not only have a unique identifier, it will also be obvious to the reader which module they belong to, and therefore what purpose they have. So while fixing the namespace conflicts, you gain readability at the same time.
Something like the above could be the first steps to implementing a formal coding standard, something you need to do sooner or later anyway as a professional programmer.
I suggest you define a wrapping header that redefines all of the functions and structures exported by the stack in terms of your own types. This header is then included in your system files but not in the stack files (where it would conflict). You can then compile and link but there is a weak point at the interface. If you select your types correctly in your redefinitions, it should work correctly, leaving only an maintenance problem on each update from the stack supplier...
I think that I've come up with a reasonable workaround, for the time being, but as Lundin stated, a formal coding standard is needed for a long-term solution.
Basically what I did was to move the inclusion of the required stack header file to before the inclusion of our in-house type definitions file. Then, between those two includes I added a compiler macro to set a defined constant dependent on whether the stack's header file single-include protection definition has been defined. Then, I used that conditional defined constant as a conditional compile option in our in-house type definition file to prevent the conflicting data-types from being re-defined. It's a little sloppy, but progress can only be made in incremental steps.
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.
I have a rather large project I'm porting, and in one of the MANY headers I've included a file that contains a struct definition for pmc_mdep. (prior in the file its just declared, but later its actually defined).
Trying to compile it gives me errors about that struct being an incomplete type (which I believe means that it's lacking a definition).
When I run the preprocessor over this project, it does include that file, but the preprocessor output does not have the struct definition (but does include enum's from that file).
Is there a method to figure out why some of a header file gets to the preprocessor output, and some does not?
TIA
(Also, this is not the only compile error, the port is half done but it should be at least getting past this part)
I usually just track back from the structure to find all the enclosing "#ifdef" and "#if" lines that the preprocessor will encounter and see which one is controlling the removal of the structure from the input stream into the compiler.
That generally works pretty quickly for all but the hairiest of header files (i.e., those with a great many nested conditional compile statements). For those, I generally have a look at the preprocessor output to identify the last line in the header file that made it to the compiler input stream.
Almost certainly the next line will be a conditional compile statement where you haven't met the condition for inclusion.
For example, if this is the header file, you would need to track back to see that _KERNEL should be defined in order to get the declaration and definition.
I'm afraid not; you will have to look for #ifdefs that surround your area of interest and track down why those symbols are not defined. If it's porting to Linux/UNIX and you are missing things from the standard headers, you might have not defined the right _XOPEN_SOURCE or _BSD_SOURCE in your Makefile or config.h .
The most likely reason is there's a #define somewhere around the definition. Since the corresponding symbol is not defined or defined to some other value the definition is not included even when the header itself is included. You'll have to inspect this manually.
Raymond Chen has a blog post about this.
You may find yourself in a twisty maze of #ifdefs. Or you may be wondering why your macros aren't working.
I have these lines in my header file:
#define MM_BUSY 0x0001
#define MM_IDLE 0x0002
but when I try to use them, I get errors.
sample.cpp(23): error C2065: 'MM_BUSY': undeclared identifier
sample.cpp(40): error C2065: 'MM_IDLE': undeclared identifier
Any idea why this is happening?
Solution: Use #error to track down the problem the same way you'd scatter printf around to track down a regular bug.
Source: Use the #error directive to check whether the compiler even sees you
I do not think that there is a better way beside checking the preprocessor output to know why one file is included or not. Here is the gcc's preprocessor's output format that may help you understand the preprocessor's ouput.
Also, another way you may have a try to compare the outputs between that you are porting and the existing one.
You said:
I have a rather large project I'm porting, and in one of the MANY headers I've included a file that contains a struct definition for pmc_mdep. (Prior in the file its just declared, but later its actually defined).
Trying to compile it gives me errors about that struct being an incomplete type (which I believe means that it's lacking a definition).
This error can occur if you try to embed a pmc_mdep into some other structure before you have defined a pmc_mdep fully. Note that you can embed pointers to incomplete types into structures, but not actual instances of the incomplete type.
You also discuss running the preprocessor over the file that should define the structure, and you see enums form the header, but not the structure definition. That suggests that maybe you have a stray comment that is removing the structure unintentionally, or perhaps you have the structure definition embedded between #ifdef XXX and #endif but XXX is not defined when you do the compilation. It could even be #if 0.
I'd run the C preprocessor on just the header that contains the structure definition to see what that produces; it will be shorter than trying to look at the output for the entire program (source file). If I couldn't spot the issue swiftly, I'd mark parts with something like stray enums to see which ones get through and which ones don't.