包括外部声明的枚举在内的问题-C代码

时间:2018-11-18 20:16:10

标签: c enums header header-files enumeration

更新:问题已解决。这是正确编译的代码。

---instruction.h---
#ifndef INSTRUCTION_H
#define INSTRUCTION_H

typedef enum OPCODE {ADD = 0x20,ADDI = 0x8,SUB = 0x22,MULT = 0x18,BEQ = 0x4,LW = 0x23,SW = 0x2B} opcode;
/*opcode is OPCODEs alias*/
typedef struct INSTRUCTION {
    opcode op;
    int rs;
    int rt;
    int rd;
    int Imm;
} inst;
/*inst is INSTRUCTIONs alias*/
#endif // INSTRUCTION_H

---parser.c---
#include <stdio.h>
#include "instruction.h"
void parser(char *instruction)
{
    /*Parse character string into instruction components*/
    inst set1 = {LW,0,1,2,0};
    printf("parsing");
};

int main()
{
    char *instruction;
    instruction = NULL;
    parser(instruction);
};
/*pass in pointer for instruction being passed in*/
/*pointing to address of instruction being passed in*/
/*Parser return type is struct inst*/

我似乎无法在我的主要c文件中识别我的枚举类型“ opcode”。我包括了头文件。我对C还是很陌生,所以一段时间以来在这个问题上没有做太多的事情,想看看是否有人知道我为什么收到下面的错误消息。我的猜测是链接头文件无法正常工作。非常感谢您的帮助。enter image description here

---instruction.h----

#ifndef INSTRUCTION_H
#define INSTRUCTION_H

typedef enum {add = 32,addi = 8,sub = 34,mult = 24,beq = 4,lw = 35,sw = 43}opcode;
extern opcode oper;
typedef struct {
    opcode op;
    int rs;
    int rt;
    int rd;
    int Imm;
}inst;
#endif // INSTRUCTION_H

---Parser.c---

#include <stdio.h>
#include "instruction.h"
void parser(char *inst)
{
    /*Parse character string into instruction components*/
    struct inst{lw,0,1,2,0};

};

int main()
{
    char *instruction;
    instruction = NULL;
    parser(instruction);
};

2 个答案:

答案 0 :(得分:0)

struct inst{lw,0,1,2,0};

这看起来应该是变量声明,但我看不到变量的名称。试试:

struct inst name_of_the_variable = {lw,0,1,2,0};

请注意,enum值是全局常量,因此给它们起类似lw的名称可能不是变量的好主意。标准做法是对名称使用大写字母,并给它们加上前缀...例如OPCODE_ADDOPCODE_LW等。

答案 1 :(得分:0)

这不是有效的变量定义:

struct inst{lw,0,1,2,0};

没有定义struct inst,只有inst,没有变量名,您需要=才能使用初始化程序。要创建此类型的变量并将其初始化,您需要:

inst myinst = {lw,0,1,2,0};

此外,您的函数还有一个名为inst的参数,它会掩盖类型inst。您需要给它起一个不同的名字:

void parser(char *instruction)