Unknown type name with typedef struct in C
Thoughts:
- It's
#ifndef
, not#ifdef
. You want to run that code ifMONSTER_H_
hasn't been defined yet. - The definition of the struct normally goes in the header file.
Putting all of this together, we have:
Monster.h
#ifndef MONSTER_H_
#define MONSTER_H_
typedef struct EnemyStats {
int EnemyHP;
int VictoryExp;
int EnemyLevel;
} EnemyStats;
int Monster(int Selection);
EnemyStats MonsterStats(int Selection);
#endif
Monster.c
#include "Monster.h"
EnemyStats MonsterStats(int selection)
{
struct EnemyStats value;
return value;
}
int Monster(int selection) {
return 0;
}
GameMain.c
#include <stdio.h>
#include "Monster.h"
int main() {
EnemyStats result;
printf("%d", result.EnemyLevel);
}
Arrowkill
Updated on July 09, 2022Comments
-
Arrowkill almost 2 years
This code is written in a file named Monster.c. I have Monster.h defined in both my GameMain.c file and my Monster.c file. Inside the Monster.h file the code is:
#ifdef MONSTER_H_ #define MONSTER_H_ int Monster(int Selection); EnemyStats MonsterStats(int Selection); #endif
I then made my typedef struct in the Monster.c file and created the function to return the values for the struct.
typedef struct EnemyStats { int EnemyHP; int VictoryExp; int EnemyLevel; } EnemyStats; EnemyStats MonsterStats(int Selection) { struct EnemyStats value; switch(Selection) { case 1: value.EnemyLevel = 1; value.VictoryExp = 1; value.EnemyHP = 1; return value; case 2: value.EnemyLevel = 1; value.VictoryExp = 1; value.EnemyHP = 1; return value; ... }
In the GameMain.c file, I used this code to try and access the information stored in the struct:
EnemyStats result; ... printf("%d", result.EnemyLevel);
It gives me the error when I use gcc GameMain.c Monster.c
GameMain.c:40:2: error: unknown type name ‘EnemyStats’
GameMain.c:61:25: error: request for member ‘EnemyHP’ in something not a structure or union
If I try to add struct before EnemyStats result; it gives me this error.
GameMain.c: In function ‘main’:
GameMain.c:40:20: error: storage size of ‘result’ isn’t known
I am unsure of what I am doing wrong. Any help is appreciated.
For anybody who does not know, I am using ... to say that I am skipping code that does not affect the situation I am describing or the code is redundant
-
Arrowkill over 9 yearsYou literally just saved me from throwing my laptop with the ifndef. I had my terminal server crash last night and apparently it did not save the ifndef when I used it in Monster.h. Thank you so much for catching my stupid little errors!
-
Arif Burhan about 8 yearsWhen I use typedef I always use alternating cases: typedef list List; you may end up with a circular definition, especially if you move to Object Oriented Programming and Inherited definitions.