GCC reporting unrelated errors for include - c

I've added a new file to a project:
#ifndef PLAYER_H
#define PLAYER_H
#include "enet/enet.h" //the problem
typedef struct Player
{
ENetPeer * peer; //requires problematic include
//void * peer; //works, since no include required
} Player;
const struct Player playerEmpty;
#endif //PLAYER_H
If the include is present, I get reams of error: expected ';', ',' or ')' before numeric constant in unrelated files. If I remove the include and use void * peer instead, all is well. The enet library is included in a source file elsewhere, and works fine. I am using enet 1.3.13 (latest) and its header guards appear to be in place. This is under gcc 4.9.2.
For the record the errors are occurring in Point.h:
#ifndef POINT_H
#define POINT_H
#include <stdint.h>
#define X 0
#define Y 1
#define Z 2
typedef int16_t int16_Point2[2];
typedef int32_t int32_Point2[2];
typedef uint16_t uint16_Point2[2];
typedef uint32_t uint32_Point2[2];
typedef int16_t int16_Point3[3];
typedef int32_t int32_Point3[3];
typedef uint16_t uint16_Point3[3];
typedef uint32_t uint32_Point3[3];
#endif //POINT_H
I'm sure it's something simple - any idea what I am doing wrong?

Using single-letter macro names is a good idea in general. They might very easily replace the letters in unexpected locations (note: Macros are actually textual replacement before the actual compilation phases).
You wrote the error is occuring in Point.h. I do not think they actually occur, but are only reported here. C is notoriously bad to detect grammar errors where they actually are. Check the file which includes Point.h
Note: const struct Player playerEmpty; in a header is also likely unwanted, as that will create an object with external linkage in every compilation unit. This is different from C++: in C, there are actually no constants, but only constant variables: const is just a promise by the programmer the variable will never be changed once initialized. Even worse: you do not assign it a value, thus making it effectively 0 - global variables are initialized to all bits 0. I'm quite sure this in not intended.
Update:
If that is for points, how about:
typedef union __attribute__ ((__packed__)) {
struct {
int16_t x,y,z;
}; // anonymous union field (C99)
int16_t vec[3];
} int16_Point3;
...
// usage:
int16_Point3 point = (int16_Point3){ .x = 5, .y = 3 }; // compound literal
point.z = point.x + point.vec[1]; // other word for point.y
to get rid of the #defines and getting proper syntax.
Note __attribute__ ((__packed__)) is gcc-specific to avoid padding bytes between struct fields. That is non-standard, but other compilers often have similar features (e.g. pragma). It is required to have identical layout for the struct and the array.
That might be more readable than the indexing. Note that anonymous struct and union fields are standard.

The problem was single-character #defines. NEVER do this.
I'd been using X, Y and Z for several months, but never had problems till my inclusion of Player.h, today, which must have finally - in a roundabout way - triggered some problems in the preprocessor / compiler. Removing these returned compilation to (a semblance of) normality.
Thanks to those who helped in the comments.

Related

Circular dependency between struct and function in C

I have the following files:
A.h
#ifndef __A_H_
#define __A_H_
#include <B.h> // contains foo_t
typedef struct {
foo_t foo;
...
} baz_t;
#endif
B.h
#ifndef __B_H_
#define __B_H_
#include <A.h> // contains baz_t
typedef struct {
...
} foo_t;
extern int useful_func(baz_t d);
#endif
When I compile this B.h refuses to compile complaining error: unknown type name 'baz_t'
I am assuming this error is owing to circular dependency between the two files. But I am wondering how do I forward declare baz_t to solve this? I found answers relating to circular dependencies between structs. But I am unsure how I would solve this. I would appreciate some help here. I am looking for a strictly C99 solution.
EDIT
I previously forgot to mention this but I have already used include guards.
A very obvious solution as suggested by user KamilCuk is moving useful_func to A.h. This has also occured to me but software organization wise useful_func unfortunately belongs to B.h. This problem could be a reflection of a poor design as well.
You can use forward declaration as follows:
struct foo;
typedef struct {
struct foo foo;
...
} baz_t;
And then use it normally on B.h
That said, circular dependencies can be avoided is you define everything on a third header that you use as interface. It would be cleaner, but it's not always possible.
Typically, one would pass pointers to structures rather than passing them by value. If that would be acceptable, things are easy, since C compilers will accept a declaration:
void doSomethingWithAFoo(struct foo *it);
without regard for whether they have seen any definition for struct foo. Indeed, compilers will even accept function definitions like:
void doSomethingWithAFooTwice(struct foo *it)
{
doSomethingWithAFoo(it);
doSomethingWithAFoo(it);
}
without having to know or care about whether, where, or how struct foo is defined.
Note that an advantage of using struct tag syntax rather than typedef names is that prototypes using the struct tag syntax don't require declaring or defining anything that can't be harmlessly redeclared arbitrarily many times.

C - typedef vs #define [duplicate]

I wonder if typedef and #define are the same in c?
typedef obeys scoping rules just like variables, whereas define stays valid until the end of the compilation unit (or until a matching undef).
Also, some things can be done with typedef that cannot be done with define.
For example:
typedef int* int_p1;
int_p1 a, b, c; // a, b, c are all int pointers
#define int_p2 int*
int_p2 a, b, c; // only the first is a pointer, because int_p2
// is replaced with int*, producing: int* a, b, c
// which should be read as: int *a, b, c
typedef int a10[10];
a10 a, b, c; // create three 10-int arrays
typedef int (*func_p) (int);
func_p fp; // func_p is a pointer to a function that
// takes an int and returns an int
No.
#define is a preprocessor token: the compiler itself will never see it.
typedef is a compiler token: the preprocessor does not care about it.
You can use one or the other to achieve the same effect, but it's better to use the proper one for your needs
#define MY_TYPE int
typedef int My_Type;
When things get "hairy", using the proper tool makes it right
#define FX_TYPE void (*)(int)
typedef void (*stdfx)(int);
void fx_typ(stdfx fx); /* ok */
void fx_def(FX_TYPE fx); /* error */
No, they are not the same. For example:
#define INTPTR int*
...
INTPTR a, b;
After preprocessing, that line expands to
int* a, b;
Hopefully you see the problem; only a will have the type int *; b will be declared a plain int (because the * is associated with the declarator, not the type specifier).
Contrast that with
typedef int *INTPTR;
...
INTPTR a, b;
In this case, both a and b will have type int *.
There are whole classes of typedefs that cannot be emulated with a preprocessor macro, such as pointers to functions or arrays:
typedef int (*CALLBACK)(void);
typedef int *(*(*OBNOXIOUSFUNC)(void))[20];
...
CALLBACK aCallbackFunc; // aCallbackFunc is a pointer to a function
// returning int
OBNOXIOUSFUNC anObnoxiousFunc; // anObnoxiousFunc is a pointer to a function
// returning a pointer to a 20-element array
// of pointers to int
Try doing that with a preprocessor macro.
#define defines macros.
typedef defines types.
Now saying that, here are a few differences:
With #define you can define constants that can be used in compile time. The constants can be used with #ifdef to check how the code is compiled, and specialize certain code according to compile parameters.
You can also use #define to declare miniature find-and-replace Macro functions.
typedef can be used to give aliases to types (which you could probably do with #define as well), but it's safer because of the find-and-replace nature of #define constants.
Besides that, you can use forward declaration with typedef which allows you to declare a type that will be used, but isn't yet linked to the file you're writing in.
Preprocessor macros ("#define's") are a lexical replacement tool a la "search and replace". They are entirely agnostic of the programming language and have no understanding what you're trying to do. You can think of them as a glorified copy/paste mechanic -- occasionally that's useful, but you should use it with care.
Typedefs are a C language feature that lets you create aliases for types. This is extremely useful to make complicated compound types (like structs and function pointers) readable and handlable (in C++ there are even situations where you must typedef a type).
For (3): You should always prefer language features over preprocessor macros when that's possible! So always use typedefs for types, and constant values for constants. That way, the compiler can actually interact with you meaningfully. Remember that the compiler is your friend, so you should tell it as much as possible. Preprocessor macros do the exact opposite by hiding your semantics from the compiler.
They are very different, although they are often used to implement custom data types (which is what I am assuming this question is all about).
As pmg mentioned, #define is handled by the pre-processor (like a cut-and-paste operation) before the compiler sees the code, and typedef is interpreted by the compiler.
One of the main differences (at least when it comes to defining data types) is that typedef allows for more specific type checking. For example,
#define defType int
typedef int tdType
defType x;
tdType y;
Here, the compiler sees variable x as an int, but variable y as a data type called 'tdType' that happens to be the same size as an int. If you wrote a function that took a parameter of type defType, the caller could pass a normal int and the compiler wouldn't know the difference. If the function instead took a parameter of type tdType, the compiler would ensure that a variable of the proper type was used during function calls.
Also, some debuggers have the ability to handle typedefs, which can be much more useful than having all custom types listed as their underlying primitive types (as it would be if #define was used instead).
No. typedef is a C keyword that creates an alias for a type. #define is a pre-processor instruction, that creates a text replacement event prior to compilation. When the compiler gets to the code, the original "#defined" word is no longer there. #define is mostly used for macros and global constants.
AFAIK, No.
typedef helps you set up an "alias" to an existing data type. For eg. typedef char chr;
#define is a preprocessor directive used to define macros or general pattern substitutions. For eg. #define MAX 100, substitutes all occurrences of MAX with 100
As mentioned above, there is a key difference between #define and typedef. The right way to think about that is to view a typedef as being a complete "encapsulated" type. It means that you cannot add to it after you have declared it.
You can extend a macro typename with other type specifiers, but not a typedef'd typename:
#define fruit int
unsigned fruit i; // works fine
typedef int fruit;
unsigned fruit i; // illegal
Also, a typedef'd name provides the type for every declator in a declaration.
#define fruit int *
fruit apple, banana;
After macro expansion, the second line becomes:
int *apple, banana;
Apple is a pointer to an int, while banana is an int. In comparison. a typedef like this:
typedef char *fruit;
fruit apple, banana;
declares both apple and banana to be the same. The name on the front is different, but they are both pointers to a char.
Another reason to use typedef (which has only been mentioned briefly in other answers and yet I think is the entire reason typedef was created) is to make debugging easier when using libraries that have custom types. For example, I'll use a type-conversion error. Both the codes below will print a compile-time error saying that a char is not comparable to a string, but in different ways.
typedef char letter;
letter el = 'e';
if(el == "hello");
The above code will print something like the variable "el" of type letter (aka "char") is not compatable with type "char*"
#define letter char
letter el = 'e';
if(el == "hello");
This code will instead print the variable "el" of type char is not compatable with type "char*"
This may seem silly because I'm defining "letter" as "char", but in more complex libraries this can be extremely confusing because pointers to objects like buttons, windows, sound servers, images, and lots of other things are defined as unsigned char *, which would only be debuggable as exactly that when using the #define method.
As everyone said above, they aren't the same. Most of the answers indicate typedef to be more advantageous than #define.
But let me put a plus point of #define :when your code is extremely big, scattered across many files, it's better to use #define; it helps in readability - you can simply preprocess all the code to see the actual type definition of a variable at the place of its declaration itself.

Actual sizeof padded struct, (sum of member sizes, without padding for alignment)

sizeof() returns size of structure including padding of members for alignment. Which is fine. Don't need to pack the structure to have 0 padding.
Just need to get get(or calculate) sum of sizes of members of structure to compare (using it in static compile time assert).
When you have members small in size, they absence/difference is not get caught.
Members are mainly char arrays
Is it possible to get that number at compile time (or at run time)?
Or how else can I make sure the 'effective' size is what I expect and avoid accidental change from braking the program?
Original intention is to avoid bugs if A or B modified to be different by mistake.
Using STATIC_ASSERT( sizeof(A) == sizeof(B) )
which doesn't work for some 'small' differences due to padding.
note: A and B should be similar, but in given design it's not possible to reuse A in both parts of the program. This check is to make sure if someone changes only A or only B, it can not compiled.
You can #include the same header twice. Once with packed enabled and once without. And obviously the macro would also change the name of the packed struct to something different to the real struct name.
Here's an example. The header file, say test.h, is shown below. It shows two struct which have different unpacked sizes but same packed sizes.
#ifdef ENABLE_PACKED
#define PACKED(x) __attribute__ ((__packed__)) x##_packed
#else
#define PACKED(x) x
#endif
struct PACKED(my_struct1) {
char c1;
int i1;
char c2;
int i2;
};
struct PACKED(my_struct2) {
char c1;
char c2;
int i1;
int i2;
};
#ifdef ENABLE_PACKED
_Static_assert(sizeof(struct my_struct1_packed) ==
sizeof(struct my_struct2_packed), "Error");
#endif
#undef PACKED
Note that you really only need to define ENABLE_PACKED and #include test.h in one file for the static assert to be tested. So you can even just create a dummy.c file which includes test.h twice and have your build compile dummy.c every time but not actually use it in any real release object. That way, all your real .c files do not even need to know about this at all and can just include all header files normally.

C forward declaration query

I have a situation where two of my header files require the data structures defined in either one, i.e. no matter which order you include them it won't compile
however, one of the problem data structures only contains pointers to the data structure declared in the other header file so I would have though that technically it doesn't need to know at this point how big the data structure is so it shouldn't be complaining
A simplified example of what I mean is outlined below. I would have thought that the array of modes in Library doesn't need to know how big a Mode is, only how big a pointer to a Mode is therefore the compiler shouldn't complain if it hasn't yet seen the declaration of Mode in the other header file.
header_1.h
typedef struct
{
Mode **modes;
} Library;
header_2.h
typedef struct
{
int number;
char *name;
} Mode;
It doesn't need to know the size, but it must have seen a declaration. A forward declaration
typedef struct Mode Mode;
before the definition of struct Library suffices.
As currently written, your example does not show the mutual cross-referencing that you mention in the question.
The compiler must be told something about each type it uses. You could use in header_1.h just:
typedef struct Mode Mode;
typedef struct
{
Mode **modes;
} Library;
That would make it compile, at least. The compiler doesn't need the details, but it does need to know that Modes is a type.
Edit:
Note that header_2.h should be modified for this to work. You have to ensure that each typedef appears just once. After you have the typedefs in place, you specify the structure content (definition) once, and you omit the keyword typedef and the typedef name from the structure definition. And you have to decide on exactly the cross-references will be managed. For example, should header_1.h include header_2.h anyway.
I don't remember encountering a case where I really needed mutually referencing structures (in quite a long time programming — long enough that I could have forgotten a example). I do now remember a case of structures mutually referencing each other; it was in a version of make originally written for Minix. I still regard such a requirement as somewhat 'pathological' (or, if you prefer, as a 'code smell') and as something to be avoided whenever possible. If you really must manage it, then the section below explains how I'd go about doing it (and more or less how the make program did go about it).
Mutually-referencing structures
If you truly have two mutually referencing structures, you should (re)consider why you think two headers are better than one. If you still need two headers, you use an idiom like:
header_1.h
#ifndef HEADER_1_H_INCLUDED
#define HEADER_1_H_INCLUDED
#ifndef TYPEDEF_MODE
#define TYPEDEF_MODE
typedef struct Mode Mode;
#endif
#ifndef TYPEDEF_LIBRARY
#define TYPEDEF_LIBRARY
typedef struct Library Library;
#endif
struct Library
{
...
Mode **modes;
...
};
#endif /* HEADER_1_H_INCLUDED */
header_2.h
#ifndef HEADER_2_H_INCLUDED
#define HEADER_2_H_INCLUDED
#ifndef TYPEDEF_MODE
#define TYPEDEF_MODE
typedef struct Mode Mode;
#endif
#ifndef TYPEDEF_LIBRARY
#define TYPEDEF_LIBRARY
typedef struct Library Library;
#endif
struct Mode
{
...
Library **liblist;
...
};
#endif /* HEADER_2_H_INCLUDED */
The repeated typedef 'detection' code is not nice; a single header is better, in my estimation. However, you can include header_1.h and header_2.h above in either order and it should compile.
I believe this is happening because "Mode" is a type defined using typedef and its not the name of the struct. You will either need to explicitly forward declare it or you can try using the code structured as follows:
header_1.h
typedef struct
{
struct _Mode_t **modes;
} Library;
header_2.h
typedef struct _Mode_t
{
int number;
char *name;
} Mode;

Are typedef and #define the same in c?

I wonder if typedef and #define are the same in c?
typedef obeys scoping rules just like variables, whereas define stays valid until the end of the compilation unit (or until a matching undef).
Also, some things can be done with typedef that cannot be done with define.
For example:
typedef int* int_p1;
int_p1 a, b, c; // a, b, c are all int pointers
#define int_p2 int*
int_p2 a, b, c; // only the first is a pointer, because int_p2
// is replaced with int*, producing: int* a, b, c
// which should be read as: int *a, b, c
typedef int a10[10];
a10 a, b, c; // create three 10-int arrays
typedef int (*func_p) (int);
func_p fp; // func_p is a pointer to a function that
// takes an int and returns an int
No.
#define is a preprocessor token: the compiler itself will never see it.
typedef is a compiler token: the preprocessor does not care about it.
You can use one or the other to achieve the same effect, but it's better to use the proper one for your needs
#define MY_TYPE int
typedef int My_Type;
When things get "hairy", using the proper tool makes it right
#define FX_TYPE void (*)(int)
typedef void (*stdfx)(int);
void fx_typ(stdfx fx); /* ok */
void fx_def(FX_TYPE fx); /* error */
No, they are not the same. For example:
#define INTPTR int*
...
INTPTR a, b;
After preprocessing, that line expands to
int* a, b;
Hopefully you see the problem; only a will have the type int *; b will be declared a plain int (because the * is associated with the declarator, not the type specifier).
Contrast that with
typedef int *INTPTR;
...
INTPTR a, b;
In this case, both a and b will have type int *.
There are whole classes of typedefs that cannot be emulated with a preprocessor macro, such as pointers to functions or arrays:
typedef int (*CALLBACK)(void);
typedef int *(*(*OBNOXIOUSFUNC)(void))[20];
...
CALLBACK aCallbackFunc; // aCallbackFunc is a pointer to a function
// returning int
OBNOXIOUSFUNC anObnoxiousFunc; // anObnoxiousFunc is a pointer to a function
// returning a pointer to a 20-element array
// of pointers to int
Try doing that with a preprocessor macro.
#define defines macros.
typedef defines types.
Now saying that, here are a few differences:
With #define you can define constants that can be used in compile time. The constants can be used with #ifdef to check how the code is compiled, and specialize certain code according to compile parameters.
You can also use #define to declare miniature find-and-replace Macro functions.
typedef can be used to give aliases to types (which you could probably do with #define as well), but it's safer because of the find-and-replace nature of #define constants.
Besides that, you can use forward declaration with typedef which allows you to declare a type that will be used, but isn't yet linked to the file you're writing in.
Preprocessor macros ("#define's") are a lexical replacement tool a la "search and replace". They are entirely agnostic of the programming language and have no understanding what you're trying to do. You can think of them as a glorified copy/paste mechanic -- occasionally that's useful, but you should use it with care.
Typedefs are a C language feature that lets you create aliases for types. This is extremely useful to make complicated compound types (like structs and function pointers) readable and handlable (in C++ there are even situations where you must typedef a type).
For (3): You should always prefer language features over preprocessor macros when that's possible! So always use typedefs for types, and constant values for constants. That way, the compiler can actually interact with you meaningfully. Remember that the compiler is your friend, so you should tell it as much as possible. Preprocessor macros do the exact opposite by hiding your semantics from the compiler.
They are very different, although they are often used to implement custom data types (which is what I am assuming this question is all about).
As pmg mentioned, #define is handled by the pre-processor (like a cut-and-paste operation) before the compiler sees the code, and typedef is interpreted by the compiler.
One of the main differences (at least when it comes to defining data types) is that typedef allows for more specific type checking. For example,
#define defType int
typedef int tdType
defType x;
tdType y;
Here, the compiler sees variable x as an int, but variable y as a data type called 'tdType' that happens to be the same size as an int. If you wrote a function that took a parameter of type defType, the caller could pass a normal int and the compiler wouldn't know the difference. If the function instead took a parameter of type tdType, the compiler would ensure that a variable of the proper type was used during function calls.
Also, some debuggers have the ability to handle typedefs, which can be much more useful than having all custom types listed as their underlying primitive types (as it would be if #define was used instead).
No. typedef is a C keyword that creates an alias for a type. #define is a pre-processor instruction, that creates a text replacement event prior to compilation. When the compiler gets to the code, the original "#defined" word is no longer there. #define is mostly used for macros and global constants.
AFAIK, No.
typedef helps you set up an "alias" to an existing data type. For eg. typedef char chr;
#define is a preprocessor directive used to define macros or general pattern substitutions. For eg. #define MAX 100, substitutes all occurrences of MAX with 100
As mentioned above, there is a key difference between #define and typedef. The right way to think about that is to view a typedef as being a complete "encapsulated" type. It means that you cannot add to it after you have declared it.
You can extend a macro typename with other type specifiers, but not a typedef'd typename:
#define fruit int
unsigned fruit i; // works fine
typedef int fruit;
unsigned fruit i; // illegal
Also, a typedef'd name provides the type for every declator in a declaration.
#define fruit int *
fruit apple, banana;
After macro expansion, the second line becomes:
int *apple, banana;
Apple is a pointer to an int, while banana is an int. In comparison. a typedef like this:
typedef char *fruit;
fruit apple, banana;
declares both apple and banana to be the same. The name on the front is different, but they are both pointers to a char.
Another reason to use typedef (which has only been mentioned briefly in other answers and yet I think is the entire reason typedef was created) is to make debugging easier when using libraries that have custom types. For example, I'll use a type-conversion error. Both the codes below will print a compile-time error saying that a char is not comparable to a string, but in different ways.
typedef char letter;
letter el = 'e';
if(el == "hello");
The above code will print something like the variable "el" of type letter (aka "char") is not compatable with type "char*"
#define letter char
letter el = 'e';
if(el == "hello");
This code will instead print the variable "el" of type char is not compatable with type "char*"
This may seem silly because I'm defining "letter" as "char", but in more complex libraries this can be extremely confusing because pointers to objects like buttons, windows, sound servers, images, and lots of other things are defined as unsigned char *, which would only be debuggable as exactly that when using the #define method.
As everyone said above, they aren't the same. Most of the answers indicate typedef to be more advantageous than #define.
But let me put a plus point of #define :when your code is extremely big, scattered across many files, it's better to use #define; it helps in readability - you can simply preprocess all the code to see the actual type definition of a variable at the place of its declaration itself.

Resources