santiag
santiag

Reputation: 21

Typedef nested structure in union, .c and .h file

How I should declare this union in header file?

#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;

I declare it this way and I can't use dataTime in my main function:

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

typedef union _TDATETIME TDATETIME

#endif /* DS3231_H_ */

Compiler generates the following error:

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

Upvotes: 0

Views: 1284

Answers (3)

user5650204
user5650204

Reputation: 1

What do you want to do?

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

  2. if the struct below in the header file, then "TDATETIME dateTime" should in the .c file.

    typedef union {

    ... } DATETIME;

for your infomation

Upvotes: 0

dbush
dbush

Reputation: 224457

If all your header file has is this:

typedef union _TDATETIME TDATETIME;

That just sets up the typedef, but does not define the union. You need to define both the union and the typedef that goes with it. Also, if there's a variable of this type that you want to use across multiple files, place an extern declaration for that variable in the header file, then define it in one C file:

In 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_ */

In ds3221.c:

#include "ds3221.h"

TDATETIME dateTime;

In main.c:

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

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

Upvotes: 3

EylM
EylM

Reputation: 6103

In C, you must use the union keyword to declare a union variable. In C++, the union keyword is unnecessary:

union TDATETIME dateTime;

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

Upvotes: 0

Related Questions