【问题标题】:C preprocessor #error in header file included in multiple source files多个源文件中包含的头文件中的 C 预处理器#error
【发布时间】:2016-04-25 18:50:28
【问题描述】:

我有两个源文件 main.c 和 datamgr.c - 以及两个头文件 config.h 和 datamgr.h 我们使用的测试系统需要这些文件,而且只有这些文件。

main.c:

#include "datamgr.h"
#include "config.h"

int main() {
    custom_type a = 1;

    a = foo();
    return 0;
}

datamgr.c:

#include "datamgr.h"
#include "config.h"

custom_type foo() {
    custom_type a = 1;
    return a;
}

datamgr.h:

#ifndef DATAMGR_H
#define DATAMGR_H

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

custom_type foo();

#endif

config.h:

#ifndef CONFIG_H
#define CONFIG_H

#ifndef SET_MAX_TEMP
#error "Max temperature not set."
#endif

#ifndef SET_MIN_TEMP
#error "Max temperature not set."
#endif

typedef custom_type uint16_t

#endif

现在,问题是我只能在 main.c 中定义 SET_MAX_TEMPSET_MIN_TEMP,但是 main.c 和 datamgr.c 都需要头文件。因此,如果我在 datamgr.c 中未定义它们,则会出现编译器错误。但是,如果我确实在 datamgr.c 中定义它们,然后在 main.c 中覆盖它们,我会得到一个不同的编译器错误。

对于如何让这个可怕的设置工作的任何帮助,我们将不胜感激。

【问题讨论】:

  • 为什么只能在main.c中定义?您应该能够(仅)在头文件中定义它们,并且它适用于所有文件。
  • 因为 main.c 是我们的测试系统用来实现测试场景的文件。因此,如果它们在 main.c -> 错误中未定义。测试系统未触及 datamgr.c 和两个头文件。

标签: c include c-preprocessor


【解决方案1】:

编译时可以直接传递这些defines:

gcc -DSET_MAX_TEMP -DSET_MIN_TEMP <your files>

【讨论】:

    【解决方案2】:

    在 datamgr.c 中:

    #define SET_MAX_TEMP
    #define SET_MIN_TEMP
    
    #include "datamgr.h"
    #include "config.h"
    
    #undef SET_MAX_TEMP
    #undef SET_MIN_TEMP
    

    【讨论】:

      【解决方案3】:

      在评论中,你说:

      因为 main.c 是我们的测试系统用来实现测试场景的文件。

      在这种情况下,请确保测试系统在编译器的命令行中为每个正在编译的文件定义了这些宏。

      【讨论】:

      • 我应该更清楚,测试系统是为了我们大学测试我们代码的功能。无法更改。
      • @fakeskuH 听起来你需要和老师的助理谈谈,然后问问你应该怎么做。明智的解决方案是#define config.h 或 datamgr.h 中的 MAX 和 MIN。如果他们想让你做一些不同的事情,那么他们需要告诉你那是什么。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      相关资源
      最近更新 更多