1

我在项目中添加了一个新文件:

#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

如果include存在,我会得到大量error: expected ';', ',' or ')' before numeric constant不相关的文件。如果我删除includevoid * peer改用,一切都很好。enet 库包含在其他地方的源文件中,并且工作正常。我正在使用 enet 1.3.13(最新),它的标头保护似乎就位。这是在 gcc 4.9.2 下。

作为记录,错误发生在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

我敢肯定这很简单-知道我做错了什么吗?

4

2 回答 2

2

一般来说,使用单字母宏名称是一个好主意。它们可能很容易替换意外位置的字母(注意:宏实际上是在实际编译阶段之前的文本替换)。

你写的错误发生在 Point.h 中。我认为它们实际上并没有发生,但仅在此处报告。众所周知,C 很难检测到语法错误的实际位置。检查包含 Point.h 的文件

注意:const struct Player playerEmpty;在标头中也可能不需要,因为这将在每个编译单元中创建一个具有外部链接的对象。这与 C++ 不同:在 C 中,实际上没有常量,只有常量变量const这只是程序员的承诺,变量一旦初始化就永远不会改变。更糟糕的是:您没有为它分配一个值,从而使其有效0- 全局变量被初始化为所有位 0。我很确定这不是故意的。

更新:

如果那是为了积分,怎么样:

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

摆脱#defines 并获得正确的语法。

注意__attribute__ ((__packed__))是 gcc 特定的,以避免在结构字段之间填充字节。这是非标准的,但其他编译器通常具有类似的功能(例如pragma)。结构和数组的布局必须相同。

这可能比索引更具可读性。请注意,匿名结构和联合字段是标准的。

于 2015-06-27T15:43:03.333 回答
1

问题是单字符#defines。永远不要这样做。

我一直在使用X,YZ几个月,但直到Player.h今天我包含 , 之前从来没有遇到过问题,这一定最终 - 以一种迂回的方式 - 引发了预处理器/编译器中的一些问题。将这些返回的编译删除为(表面上的)常态。

感谢那些在评论中提供帮助的人。

于 2015-06-27T15:30:43.070 回答