I have code for bool typedef
typedef enum bool {
false,
true,
} bool;
in two headers files if it is not included in the ultimate parent header file, child C files cannot, of course, use type bool, though children of the lesser header file that also defines it can.
However if I define it in the ultimate parent header file then the lesser header file definition errors with "bool has already been declared in the current scope"
I need a solution for the lesser header where it may be included on a project that may or may not have already defined bool... What is the best way to do this??
Ta
First of all, if you're working with a C99 compiler or later, there's already a standard Boolean type defined in stdbool.h.
Secondly, you can usually avoid testing against true and false values directly, and I've found over the years that this actually leads to code that's a little easier to read and less error-prone (that's just a personal opinion, though -- YMMV).
The immediate solution is to surround your typedefs with an include guard:
#ifndef BOOL_DEFINED
#define BOOL_DEFINED
typedef enum bool {
false,
true
} bool;
#endif
This will keep the type from being declared more than once. However, as you've discovered, putting the same type definition in two different headers is a recipe for heartburn. It would be better to put the definition in its own header file (with the include guards as shown above), and then include that file where necessary.
I'd factor this and any other shared definitions out into a types.h header which is included by each of your other headers.
Alternatively, you could do something like
#ifndef BOOL_DEFINED
#define BOOL_DEFINED
typedef enum bool {
false,
true,
} bool;
#endif
in both headers.
Related
I want to make struct members accessible for all, but writable only for specially marked code.
Using something like this in header file:
#ifdef ALLOW_WRITE
#define EXTCONST
#else
#define EXTCONST const
#endif
and placing EXTCONST everywhere in struct typedefs like this:
typedef struct {
int a;
} EXTCONST typename;
Corresponding .c file have #define ALLOW_WRITE at beginning, other files have not.
I'm nearly sure that this will work as expected, at least without agressive optimizations turned on.
Two questions:
1) will this work properly with maximum optimizations enabled?
2) is this way correct according to C standards?
NOTE: i know that this can be done via getter functions, but i think that st->a->b looks far better and more intuitive than a_get_b(st_get_a(st))
SUMMARY:
At least two people says that such hidden typecasting is not safe and no one says it is ok.
So i will use "improved" way to do read-noly access check.
#ifdef CONST_CHECK
#ifdef ALLOW_WRITE
#define EXTCONST
#else
#define EXTCONST const
#endif
#else
#define EXTCONST
#endif
And run the compiler two times for source files in question: one with -DCONST_CHECK to emit all warnings about unauthorized write access, and the second without this flag to produce compiled object file without any possible harmful side affects from compiler optimizations.
This is a dangerous way to do, if you include a header using EXTCONST in a source defining ALLOW_WRITE and also in an other source without defining ALLOW_WRITE the two sources will not see the same definitions.
So for instance in a source the compiler can suppose something will not change because const, but because it calls something in the other source changing the value there is an inconsistency.
All the sources have to share the same definitions.
I an developing a lib for use on an embedded platform. I have code in a header that is part of the lib with
typdef enum bool {false, true} bool;
If the lib user has already defined a type named bool, how can I code this so that my lib does not attempt to re-declare it?
Currently I have used #defines
#ifndef _BOOL
#define _BOOL
typedef enum bool{...
#endif
however this depends on a user that has bool defined also defining _BOOL
Is there a way of checking if types`with specific names already exist?
(Note this is a C Question, not C++, and neither I nor my assumed lib user is using stdbool, Ta)
You can't.
Your library probably should just define its own, distinct boolean type:
typedef enum { libname_false, libname_true } libname_bool;
Within your library implementation you could alias those to more convenient names as you desire.
Incidentally, you should not name preprocessor macros with leading underscores; those names are reserved for the compiler.
I would go a way you going now, supplying some kind of your_lib_config.h with #defines like HAS_BOOL_DEFINED or anything similar which affects your library configuration. So user will be responsible to adjust settings in config header before using your library.
As for working on a larger project, I want to throw in some own types (e.g. myType). The "rushing in"-approach would be, to put those typedefs into an header (lets say myType.h), together with a bunch of functions working on those types.
If I use the new type somewhere, I include myType.h to my source-file. Fine.
But if I want to use the new type somewhere as an argument in a function-signature, I need to include the myType.h to the header of the module containing the function. With one or another typedef, this seems to be okay for me, but the more types I have, the more includes in headers I need, possible including further header, while using type including other own types. This is resulting in what I call "dependency hell".
Is there a clever, stylish, best practice, what-so-ever way to solve this dilemma?
I'm aware of the possibility to pass those types as void-pointer, casting them back inside the function, but then I loose important type-checking from the compiler.
Furher, extern is considered worst-practice around here..
EDIT:
In detail:
myType.h:
#include "otherType.h"
typedef struct {
char Name[32];
int Size;
otherType someType;
} myType;
processSomeHow(myType _myType, int NewSize);
otherType.h
#define SOME_CONST 32
typedef struct { [...] } otherType;
someModule.h:
#include "myType.h"
int specialProcessSomeHow(myType _myType);
someModule.c:
int specialProcessSomeHow(myType _myType)
{
int Size = 64;
return(processSomeHow(_myType, Size));
}
Now I include otherType.h indirectly to someModule.h, even worse, I include it to every module, that includes someModule.h. Now I have a SOME_CONST everywhere and it's hard to figure out, from where it comes. I have to maintain two include trees.
like in the gtk library you can use one headfile and split it on your needs.
type.h
- myType.h
-- someType.h
- otherType.h
- List item
and on your CONST-Problem:
If you just need it for one c.file. Don't use them in HeaderFile.
And you could name them like "MY_TYPE_SOME_CONST" or "OTHER_TYPE_SOME_CONST";
//EDIT:
to make it clear: just add 'this.h' file and name it.
#ifndef TYPE_H_
#define TYPE_H_
#include myType.h
#include someType.h
#include otherType.h
#endif /* TYPE_H_ */
now you can use "#include this.h" for each file you need your types.
(this.h is not real, name it to something unique)
You can (and probably should) use forward declarations for your custom types. See details here: typedef stuct with forward declaration in C
Your interfaces (the headers) should have incomplete types (i.e. pointers to your custom types) and inside the source code (c files) you should include the My_Type.h.
You're worrying unnecessarily : There is no 'dependency hell', precisely because you are giving the compiler all the information it needs to do it's job.
Here's my rules for this:
Always, always use header guards.
Every .h file should
explicitly #include every other .h file it needs in order to compile,
and no more.
So if b.h uses a type from a.h, then b.h must #include "a.h". If b.c uses functions from a.h, but b.g doesn't use types from it, then b.c should #include a.h.
There's no need for extern keyword on functions in .h files, because IIRC modern compilers deduce this correctly.
Using extern for global variables may well be frowned on, with good
reason.
Cluttering of global namespace. C++ namespaces address this, but in C you have to use naming conventions for all global types, functions and #defines. Pick a convention that works for you : I've seen teams successfully use a LETTER-DIGIT-DIGIT prefix for every source file, so foo.h might become (for example) B04_foo.h, and all functions/types get the same B04_ prefix. It's a bit crude, but it works. As I say, pick one that works for you.
I have a double type bool so have added to a header:
typedef double bool;
extern bool true;
extern bool false;
with:
bool true = 1.0;
bool false = 0.0;
in the corresponding C file.
However I now have the errors multiple definition of true, and the same for false, pointing to the first line of the first function in the C file. the error that says 'previous declaration was here' points to the same line... it doesnt make any difference which function is placed first in the file it always points to it.
My header files, though included via a common header file, do have include guards so I hopefully shouldn't have multiple declaration of true and false there.
I have changed the typedef to tBool with vars tTrue and tFalse, which solves the problem, but I don't get why it occurred in the first place? As there are still some bool types using true and false in the code it seems like the compiler may have a definition for true and false as ints already... though I didn't think C did this
Im using dev-c++ 4.9.9.2 IDE that uses mingw, though Im not sure which version mingw.
Anyone know why this happened?
It sounds to me like your parameter is not really a Boolean value at all. You have a floating point parameter with special cases for the discrete numbers 0.0 and 1.0. Create two double constants instead of a type.
C99 added definitions for the type _Bool, a macro bool, a macro true, and a macro false. Try inserting the following in your header:
#if __bool_true_false_are_defined
# error "stdbool.h has been included"
#endif
#ifdef bool
# error "bool is already DEFINED"
#endif
#ifdef true
# error "true is already DEFINED"
#endif
#ifdef false
# error "false is already DEFINED"
#endif
If any of these fire, then you are including stdbool.h somewhere. You should be able to #undef the three macros and then set up your types safely. Of course, this will probably break if someone else expects bool to be a small integer value and has more style problems that you can shake a stick at.
ISO/IEC 9899:1999 does make a concession to the fact that many groups have already defined their own Boolean types before it was added to the Standard. This is the rationale for defining bool, true, and false as macros instead of new keywords. However, the following warning is explicitly included:
7.26.7 Boolean types and values <stdbool.h>
The ability to undefine and then perhaps redefine the macros bool, true, and false is an obsolescent feature.
I am programing in C language in Linux platform . I want to know should be the order of declarations and #defines in a header file.
For example if my header file includes following thing can anyone please suggest me what should the perfect order to arrange all these declarations, function like macros , exteren declarations, etc.
This can be really beneficial for arranging all these things in a header file properly in terms of readability and coding standards.
Below is the sample header file (I want to arrange the following in a proper order) :
#include <pthread.h> // Including Header files
#include <signal.h>
#define IMAGE_DIRECTORY "Abcdefgh..." // Providing #defines
#define FAILED_TO_RECOGNIZE "Xykbkksk..."
#define PROGRESS_FRAME_COLOR "#8e8ea1"
#define FRAME_BG_COLOR "#7c90ac"
#define PRINT_FUNCTION_NAME fprintf(stderr,
"CTRL IN FUNCTION : %s\n",__func__); // Macro like functions
typedef struct {
int userId; // Structure
char name[32], rollNo[32];
char class[16], section[16];
unsigned long Id;
}data_type;
int noOfUsersList=0, usersListCount=0; // Global variables
I haven't done this for years but when I was heavily developing for Unix, MS.DOS, OS/2, NetWare, and Windows simultaneously I developed this practice:
Language #includes
Operating system #includes
#includes from other subsystems, e.g. X11.
My own application #includes.
My own local #defines for this source file.
My own forward declarations for this file.
Maybe you can reverse (1) and (2) but I found this order to work the best across quite a number of compilers and operating systems.
Coding style is subjective, personally I use the rules and methods described below, but please note that are my own opinions and no absolute truths. Yet they are based on long experience and in some cases on widely-recognized coding standards (MISRA, CERT etc).
Rules:
C programming is done in "code modules", where every module consists of a .h file and a .c file.
#includes shall always be in the .h file and never in the .h file, since the .h file should be regarded as public. You want the person that is going to use your module to know what dependencies there are.
There is never a reason to use non-const global variables in C, so where to place non-const globals and externs isn't relevant to me.
.h files shouldn't contain any definitions. This is not only bad program design, it is also an excellent way to conjure numerous hard-to-solve linker errors.
In a .h file, the following items are allowed to appear, in the stated order:
Start of header guard. (#ifndef MYHEADER_H ...)
Library #includes.
Other #includes.
Impl.-specific compiler settings such as compiler options set with #pragmas.
Public numeric constants as #defines.
Public macros.
Public type definitions, including opaque types.
Declaration of public constants (declared as extern const).
Inline function definitions (rare special case, avoid if possible).
Function prototypes.
End of header guard. #endif
In a .c file, the following items are allowed to appear, in the stated order:
Include of its own corresponding .h file.
Private numeric constants in #defines.
Private macros.
Definition of opaque types, that were declared as incomplete type in the corresponding .h file.
Private type definitions.
Definition of public constants (declared as extern const in the .h file).
Definition of private constants (static const).
Definition of private variables at file scope (static).
Declaration of private functions (declared as static type func (type param);)
Definition of the public functions declared in the .h file.
Definition of private functions.
Macro definitions with #define are not declarations. The only requirement is that macros should be defined before their usage. They stay defined until end of compilation unit, or an explicit #undef (or a redefinition...).
My stylistic convention is to define statement-like macros as having a "function" like syntax, something like:
#define PRINT_FUNCTION_NAME() fprintf(stderr, \
"CTRL IN FUNCTION: %s #%s:%d\n", __func__, __FILE__, __LINE__)
Notice the empty formal macro argument (ie first ()) and the lack of terminating semicolon (because you will use it as a quasi-function call, e.g. PRINT_FUNCTION_NAME(); statement). Notice also use of __FILE__ and __LINE__ in a debug message.
Quite often, a statement-like macro is a do{ something } while(0) because this is a syntax which has a statement like look and can always be used as a statement (including as the then part of an if, or in else branch, etc...). An example from <ncurses.h> :
#define getsyx(y,x) do { if (newscr) { \
if (is_leaveok(newscr)) \
(y) = (x) = -1; \
else \
getyx(newscr,(y), (x)); \
} \
} while(0)