Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
跨多个文件共享的C头文件中的枚举_C_Enums_Header Files - Fatal编程技术网

跨多个文件共享的C头文件中的枚举

跨多个文件共享的C头文件中的枚举,c,enums,header-files,C,Enums,Header Files,我想定义一次枚举类型,并在包含该文件时使该类型在所有其他文件中共享,但我不断遇到以下错误: $ gcc -std=c99 main.c invoc.h invoc.c main.c: In function ‘main’: main.c:12: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘pr_alg’ main.c:12: error: ‘pr_alg’ undeclared (first use in thi

我想定义一次枚举类型,并在包含该文件时使该类型在所有其他文件中共享,但我不断遇到以下错误:

$ gcc -std=c99 main.c invoc.h invoc.c
main.c: In function ‘main’:
main.c:12: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘pr_alg’
main.c:12: error: ‘pr_alg’ undeclared (first use in this function)
main.c:12: error: (Each undeclared identifier is reported only once
main.c:12: error: for each function it appears in.)
main.c:13: error: ‘FIFO’ undeclared (first use in this function)
invoc.c:7: error: expected ‘)’ before ‘myalg’
代码如下:

invoc.h

#define INVOC_H
#ifndef INVOC_H

typedef enum {FIFO, SECOND_CHANCE, RANDOM, NRU, CLOCK, AGING} alg_t;

void func1(alg_t myalg);

#endif
invoc.c

#include "invoc.h"

void func1(alg_t myalg) {
    myalg = NRU;
}
#include "invoc.h"

int main(int argc, char **argv) {

    extern alg_t pr_alg;
    pr_alg = FIFO;
    printf("PR_ALG: %d\n", pr_alg);

    return 0;
}
main.c

#include "invoc.h"

void func1(alg_t myalg) {
    myalg = NRU;
}
#include "invoc.h"

int main(int argc, char **argv) {

    extern alg_t pr_alg;
    pr_alg = FIFO;
    printf("PR_ALG: %d\n", pr_alg);

    return 0;
}
是否有任何方法可以在.h文件中定义枚举,并将其包含在所有其他文件中,以便创建该类型的不同变量并将其传递给函数

  • 您的
    invoc.h
    文件中有错误:

    #define INVOC_H
    #ifndef INVOC_H
    ...
    #endif
    
    首先定义一个宏
    INVOC\u H
    ,然后检查它是否不存在(它存在),这样预处理器就会删除其中的代码,而编译器就不会对其进行分析。
    应该是:

    #ifndef INVOC_H
    #define INVOC_H
    ...
    #endif
    
    更改后,您的代码将正常工作

  • 您不编译
    .h
    文件,只编译
    .c
    文件。这就是为什么我们将所有定义放在
    .c
    文件中,而只将声明放在
    .h
    文件中。要编译,只需执行以下操作:

    gcc -std=c99 mmu.c invoc.c
    
  • main()
    中的
    pr\u alg
    声明为
    extern
    变量。如果您提供的行是整个编译行,编译将发出链接器错误,因为变量
    pr_alg
    未定义。删除
    extern
    或在其中一个
    .c
    文件中定义具有全局存储持续时间的变量
    pr\u alg


  • 您不编译.h文件,只编译.c文件。当我不使用.h进行编译时,仍然会出现相同的错误:$gcc-std=c99 main.c invoc.c-o main在
    invoc.h
    块之前定义
    invoc\u h
    。也就是说,它永远看不到街区里的东西。哦,完全没有看到。谢谢。关于:
    void func1(alg\u t myalg){myalg=NRU;
    myalg
    的赋值只会修改局部参数(通常在堆栈上),顺便说一句:函数
    funct1()
    从未被调用。我很确定OP不需要全局变量。