【问题标题】:Typedef nested structure in union, .c and .h file联合、.c 和 .h 文件中的 Typedef 嵌套结构
【发布时间】:2015-12-07 13:10:47
【问题描述】:

我应该如何在头文件中声明这个联合?

#include <avr/io.h>
#include <stdint.h>
#include <stdio.h>
#include "i2c_twi.h"

#define DS3231_ADDR 0xd0

typedef union {
    uint8_t bytes[7];
    struct{
         uint8_t ss;
         uint8_t mm;
         uint8_t hh;
         uint8_t dayOfWeek;
         uint8_t day;
         uint8_t month;
         uint8_t year;
     };
 } TDATETIME;

 TDATETIME dateTime;

我这样声明,我不能在我的主函数中使用dataTime

#include <stdint.h>
#ifndef DS3231_H_
#define DS3231_H_

typedef union _TDATETIME TDATETIME

#endif /* DS3231_H_ */

编译器产生以下错误:

../main.c:42:26: error: ‘dateTime’ undeclared (first use in this function)
DS3231_get_dateTime( &dateTime );

【问题讨论】:

  • 你在哪里定义那个联合? n 源文件?为什么不在头文件中?您显示的错误消息是编译器显示的only消息吗?
  • typedef union _TDATETIME TDATETIME 最后错过了;
  • 我不错过 ;在末尾。我不会误将它复制到这里。这是编译器显示的完整消息: ../main.c: In function ‘main’: ../main.c:42:26: error: ‘dateTime’ undeclared (first use in this function) DS3231_get_dateTime( &dateTime ); ^ ../main.c:42:26: 注意:每个未声明的标识符对于它出现在 make 中的每个函数只报告一次:*** [main.o]
  • 你是要在main.c中定义TDATETIME 变量,还是访问union的成员?如果这样做,则需要在 header 中提供完整的 typedef。
  • 第一个代码 sn-p 来自哪个文件?

标签: c struct header-files unions


【解决方案1】:

如果你所有的头文件都是这样的:

typedef union _TDATETIME TDATETIME;

这只是设置了 typedef,但没有定义联合。您需要同时定义联合和与之配套的 typedef。此外,如果您想在多个文件中使用这种类型的变量,请在头文件中为该变量声明extern,然后在一个 C 文件中定义它:

在 ds3231.h 中:

#include <stdint.h>
#ifndef DS3231_H_
#define DS3231_H_

typedef union {
    uint8_t bytes[7];

    struct{
         uint8_t ss;
         uint8_t mm;
         uint8_t hh;
         uint8_t dayOfWeek;
         uint8_t day;
         uint8_t month;
         uint8_t year;
     };
 } TDATETIME;

 extern TDATETIME dateTime;

#endif /* DS3231_H_ */

在 ds3221.c 中:

#include "ds3221.h"

TDATETIME dateTime;

在 main.c 中:

#include <stdio.h>
#include "ds3221.h"

int main()
{
    ...
    // use dateTime
    ...
}

【讨论】:

  • dateTime 似乎在 DS3131.c 中,因此您可能应该添加有关externing 的部分。
  • 但我有 3 个文件。 main.c DS3231.c 和 DS3231.h。第二和第三是库文件。我必须有 TDATETIME 日期时间;在 DS3231.c 中。当我在 .h 文件中有 typedef union 时,我有同样的错误。
  • @santiag 在这种情况下,您需要在 DS3231.h 中添加 extern 声明,并在 DS3231.c 中添加定义。我已经更新了我的答案以反映这一点。
【解决方案2】:

在 C 中,您必须使用 union 关键字来声明联合变量。在 C++,union 关键字是不必要的:

union TDATETIME dateTime;

发件人:https://msdn.microsoft.com/en-us/library/5dxy4b7b(v=vs.80).aspx

【讨论】:

  • 但是TDATETIMEtypedef设置的类型别名,所以不需要union关键字。
  • 当我在 main.c 中拥有所有功能并且我没有 union 关键字时,它可以工作。
【解决方案3】:

你想做什么?

  1. typedef union _TDATETIME TDATETIME; typedef union TDATETIME _TDATETIME;

  2. 如果下面的结构在头文件中,那么"TDATETIME dateTime"应该在.c文件中。

    typedef 联合 {

    ... } 日期时间;

供您参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多