jparanich
jparanich

Reputation: 8994

Accessing extern struct members from different header

struggling with the below problem for too long and need a little help!

Trying to access the members of a structure from a different header but memory is a little foggy on what I'm doing wrong! I seem to recall I need to do something weird with typedef?

parseinput.h

#ifndef PARSEINPUT_H
#define PARSEINPUT_H

extern struct pitching_stat_struct pitching_home_player;

#endif

parseinput.cpp

struct pitching_stat_struct
{
    char playerID[16] = { '\0' };
    char teamID[16] = { '\0' };
    unsigned short W = 0;
    unsigned short L = 0;
    unsigned short G = 0;
} pitching_home_player;

someother.cpp

#include "parseinput.h"

void getStructElement()
{
    unsigned short playersW = pitching_home_player.W;
    // Results in below errors:
    // error C2027: use of undefined type 'pitching_stat_struct
    // error C2228: left of '.W' must have class/struct/union
}

Appreciate the help.

Upvotes: 0

Views: 41

Answers (1)

NathanOliver
NathanOliver

Reputation: 180510

It is not enough for the translation unit to have an object of the type you want to work with. It also needs to know how it is defined. Including just parseinput.h doesn't give it that definition. In order to do this you need to have

parseinput.h

#ifndef PARSEINPUT_H
#define PARSEINPUT_H

struct pitching_stat_struct
{
    char playerID[16] = { '\0' };
    char teamID[16] = { '\0' };
    unsigned short W = 0;
    unsigned short L = 0;
    unsigned short G = 0;
}

extern pitching_stat_struct pitching_home_player;

#endif

parseinput.cpp

#include "parseinput.h"

pitching_stat_struct pitching_home_player;

someother.cpp

#include "parseinput.h"

void getStructElement()
{
    unsigned short playersW = pitching_home_player.W;
    //...
}

Upvotes: 2

Related Questions