C中多次包含头文件错误

时间:2012-10-03 02:23:09

标签: c conditional-compilation

所以我有一个头文件让我们说“header.h”受到如下保护:

#ifndef __HEADER1_H
#define __HEADER1_H
//type and function def 
typedef struct
{
  float r; //process noise
  float k; //process gain
}state_t;

int get_state(state_t* state, float b);

#endif

现在我有两个其他标题,我定义如下:

 #ifdef __HEADER2_H
 #include "header.h"
//function def
 #endif

第二个标题:

#ifdef __HEADER3_H
//function
//the reason it is done this way is for cnditional compiling such that if the caller  

//defines __HEADER3_H t this file won't be included.
#include "header.h"
#endif

现在我怀疑编译器抱怨在header2和header3的源代码实现中没有检测到header.h中定义的类型和函数。所以我也在源文件中包含了header.h。现在链接器抱怨在header.h中定义的函数是多重定义的。 我的理解是因为header.h受ifndef保护,它只会被包含一次所以我没有看到问题。 这是我得到的错误:

Symbol get_state multiply defined(by kalman.o and dsp.o)

我是否有可能做出异常错误的事情?

2 个答案:

答案 0 :(得分:2)

#ifndef __HEADER1_H
#define __HEADER_H

问题是你的警卫(__HEADER_H)与你要检查的不同(__HEADER1_H)。使这两个值相同。

答案 1 :(得分:1)

头文件的典型“保护”是:

myheader.h:

#ifndef _MYHEADER
#define _MYHEADER
<do stuff>
#endif

(可选)包含myheader.h,您可以这样做:

#ifndef _MYHEADER
#include "myheader.h"
#endif

这是可选,基本上只是为了提高编译性能。

相关问题