c - 其他源文件中使用的结构

标签 c struct header structure extern

我有3个文件

//--------------reg_des.h---------------
struct reg
          {
              unsigned int i : 4;
              unsigned int j : 4;
          };
extern struct reg; 



//--------------reg_des.c---------------

struct reg xyz_reg = {.i = 2,.j = 1};


//--------------main.c---------------
#include "reg_des.c"
void  display_onmodule(struct reg xyz_reg_1)

int main()
{
   display_onmodule(xyz_reg);
}

void  display_onmodule(struct reg xyz_reg_1)
{
     .....
 }

这里我在头文件中声明了一个结构体,并在另一个源文件中初始化了结构体类型的变量。 实际上我想知道声明一个可由多个源文件使用的结构是否正确?

最佳答案

不,这不是设计程序的正确方法 - 这是使用全局变量的意大利面条式编程。几乎不存在合理使用全局(非const)变量的情况。

此外,如果您发现需要包含 .c 文件,则意味着您的设计已经完全失控。我们永远只包含 .h 文件。

修复程序的最简单方法是:

//--------------reg_des.h---------------
#ifndef REG_H // always use header guards!
#define REG_H    

struct reg  // note: this bit-field is completely non-portable
{
    unsigned int i : 4;
    unsigned int j : 4;
};

void reg_init (struct reg* r);

#endif // REG_H


//--------------reg_des.c---------------
#include "reg_des.h"    

void reg_init (struct reg* r)
{
  *r = (struct reg) {.i = 2,.j = 1};
}




//--------------main.c---------------
#include "reg_des.h"

void  display_onmodule(struct reg xyz_reg_1);

int main()
{
   struct reg xyz_reg;
   reg_init(&xyz_reg);

   display_onmodule(xyz_reg);

   // pass on xyz_reg to x different files here, etc
}

void  display_onmodule(struct reg xyz_reg_1)
{
     .....
}

还有更好的设计,带有私有(private)封装,但以上是可以接受的。

关于c - 其他源文件中使用的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47222397/

相关文章:

objective-c - 读/写文件头

python - 查找值大于列平均值的列

c函数: re-initialize a static array or declare new every call?

c - 在编译器的哪个阶段检测到标识符名称过长的错误?

c++ - std::remquo 目的和用法?

C - 创建一个匿名结构实例

c++ - 如何在结构 C++ 中使用枚举

C-Python asyncio : running discord. py 在线程中

c - 获取成员请求不是结构或 union 错误

audio - FLAC文件开头附近的那32位是什么?