简体   繁体   English

C类型定义结构不确定性

[英]C typedef struct uncertainty

Consider the following typedef struct in C: 考虑一下C中的以下typedef结构:

21:typedef struct source{
22: double  ds;             //ray step
23: double  rx,zx;          //source coords
24: double  rbox1, rbox2;   //the box that limits the range of the rays
25: double  freqx;          //source frequency
26:    int64_t  nThetas;        //number of launching angles
27:    double   theta1, thetaN; //first and last launching angle
28:}source_t;

I get the error: 我得到错误:
globals.h:21: error: redefinition of 'struct source' globals.h:21:错误:“结构源”的重新定义
globals.h:28: error: conflicting types for 'source_t' globals.h:28:错误:“ source_t”的类型冲突
globals.h:28: note: previous declaration of 'source_t' was here globals.h:28:注意:之前'source_t'的声明在这里

I've tried using other formats for this definition: 我尝试使用其他格式进行此定义:


struct source{
...
};
typedef struct source source_t;

and


typedef struct{
...
}source_t;

Which both return the same error. 两者都返回相同的错误。 Why does this happen? 为什么会这样? it looks perfectly right to me. 对我来说看起来很不错。

Are you sure you didn't include your header twice (without using #ifndef / #pragma once to avoid that)? 您确定没有两次包含标头(避免#pragma once使用#ifndef / #pragma once以避免这种情况)吗? Even if there'd been some mistake in your construct it shouldn't trigger the error "redefinition of '...'" cause it's the very first line? 即使您的构造中有一些错误,它也不应该触发错误“'...'的重新定义”,因为这是第一行吗?

The most likely cause is that your header file is being included more than once. 最可能的原因是头文件被多次包含。 You need to ensure that if this happens, the typedef is only executed once. 您需要确保这种情况下,typedef仅执行一次。

You can do this by wrapping globals.h with: 您可以通过将globals.h包装为:

  #ifndef _globals_h_
  #define _globals_h_
  [...]
  #endif

The errors say a struct source has been defined more than once. 错误表明struct source已定义多次。

Maybe you included the header file twice? 也许您两次包含了头文件?

Just to be on the safe side, be sure that your header gets only included once: put 为了安全起见,请确保您的标头仅包含一次:放

#ifndef YOUR_HEADER_FILE_NAME
#define YOUR_HEADER_FILE_NAME

at the beginning, and 一开始,

#endif

at the end of your header file: this will prevent it to be included twice or more by any source file. 在头文件末尾:这将防止任何源文件将其包含两次或更多次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM