如何在我的结构中使用typedeffed枚举?

时间:2016-09-15 14:33:25

标签: c enums

您好我正在使用日志记录系统,并希望创建一个包含记录器内部状态的结构:

#include "logger.h"
#include "main.h"
/*
 * Variables
 */

/*State of Logging*/
struct {
    bool logOn;
    static enum eLogLevel outputLevel[7];
} sLogStruct;

static struct sLogStruct gLogData;

void Log(enum eLogSubSystem sys, enum eLogLevel level, char * msg)
{

}

我在logger.h文件中定义了eLogLevel枚举:

#ifndef LOGGER_H_
#define LOGGER_H_

#include "globaldefinitions.h"

/*
 * Logger data types
 */

typedef enum eLogLevel {none, information_only, debugging, warning, error, critical};
typedef enum eLogSubSystem {coresystem, heartrate, temperature, accelerometer, communication, flash, firmwareUpdate};
/*
 * Public functions
 */

void Log(enum eLogSubSystem sys, enum eLogLevel level, char * msg);
void LogWithNum(enum eLogSubSystem sys, enum eLogLevel level, char * msg, int number);
void LogSetOutputLevel(enum eLogSubSystem sys, enum eLogLevel level);
void LogGlobalOn(void);
void LogGlobalOff(void);
void LogVersion (em_fw_version_t version);


#endif /* LOGGER_H_ */

然而,我的编译器抱怨说:

../Logging/logger.c:18:2: error: expected specifier-qualifier-list before 'static'
  static enum eLogLevel outputLevel[7];

我无法弄清楚如何解决这个问题,我想这很简单,但我不知道为什么它不接受来自logger.h文件的typedef枚举eLogLevel。 能帮助我理解吗?

2 个答案:

答案 0 :(得分:1)

您的原始代码存在不同的问题。

  • 在C中,struct的成员不能是静态的。如果你想要
  • ,请使用C ++
  • 您的typedef不正确。他们应该写:

    typedef enum {none, information_only, debugging, warning, error, critical} eLogLevel ;
    

    struct {
        bool logOn;
        eLogLevel outputLevel[7];
    } sLogStruct;
    

    typedef struct {
        bool logOn;
        eLogLevel outputLevel[7];
    } SLogStruct;
    SLogStruct sLogStruct;
    

答案 1 :(得分:0)

好的我修改了它:

#include "logger.h"
#include "main.h"
/*
 * Variables
 */

/*State of Logging*/
typedef struct {
    bool logOn;
    enum eLogLevel outputLevel[7];
} sLogStruct;

static sLogStruct gLogData;

sLogStruct * LogInternalState(void){
#if PRODUCTION
    #error "Internal state of logging protected!"
#else
    return &gLogData;
#endif /*PRODUCTION*/

}

void Log(enum eLogSubSystem sys, enum eLogLevel level, char * msg)
{

}

现在就像这样。我保持struct本身是静态的,但不是它的任何成员。感谢RomanHocke链接。

但是,我还必须更改结构声明部分

struct {
    bool logOn;
    static enum eLogLevel outputLevel[7];
} sLogStruct;

static struct sLogStruct gLogData;

到typedef结构类型的东西:

/*State of Logging*/
typedef struct {
    bool logOn;
    enum eLogLevel outputLevel[7];
} sLogStruct;

static sLogStruct gLogData;

否则编译器会说:

../Logging/logger.c:21:26: error: storage size of 'gLogData' isn't known
 static struct sLogStruct gLogData;

实际上我认为typedef结构和结构定义有点相同......