多个源文件中包含的头文件中的C预处理器#error

时间:2016-04-25 18:50:29

标签: c include c-preprocessor multiple-files

我有两个源文件,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_TEM P,但main.c和datamgr.c都需要两个头文件。因此,如果我在datamgr.c中未定义它们,我会收到编译器错误。但是,如果我在datamgr.c中定义它们并稍后在main.c中覆盖它们,我会得到不同的编译器错误。

请非常感谢有关如何使这个可怕的设置工作的任何帮助。

3 个答案:

答案 0 :(得分:1)

您可以在编译时直接传递这些define

gcc -DSET_MAX_TEMP -DSET_MIN_TEMP <your files>

答案 1 :(得分:0)

在datamgr.c中执行:

#define SET_MAX_TEMP
#define SET_MIN_TEMP

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

#undef SET_MAX_TEMP
#undef SET_MIN_TEMP

答案 2 :(得分:0)

在评论中,你说:

  

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

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

相关问题