Re: External structs - newbie question
- From: "John Bode" <john_bode@xxxxxxxxxxx>
- Date: 10 Nov 2006 10:15:00 -0800
Simon wrote:
I'm having difficulty with a struct in two of my c files.
The header file for csd.c (the main program) contains the typedef for a
struct called tiles. There is only one struct in use (called "map")
throughout the time that the program is run, and as it's used by
virtually all of the functions it's currently a global. I realise that
this is probably bad practice but I'm still pretty far down the curve
when it comes to c.
The file org.c contains some code which alters certain of the values
within "map". I'd like to declare "map" in csd.c and then use extern
to tell org.c that it exists. Unfortunately, nothing that I do seems
to be able to achieve this. I'm definitely including the typedef in
both files, but if I put a statement like "extern map" in org.c and try
and compile it gives an error "subscripted value is neither array nor
pointer" when it gets to the line "map[i][j].terrain = 1;".
The only way that I can get the thing to compile is to have a header
file shared by both csd.c and org.c which contains the typedef followed
by the declaration of the global variable map. This makes me nervous
because as far as I can see the global "map" is being declared twice -
once by each of the files.
Any ideas?
Simon
Put an extern declaration of map in the header file, and put the
defining declaration of map in csd.c:
/* header file */
typedef struct ... tiles;
/*
* Makes the identifier visible to other translation units,
* but indicates that the defining occurrence is
* somewhere else.
*/
extern tiles map;
/* csd.c */
#include "header.h"
....
/*
* Defining declaration of map; this is done at file scope, outside
* of any function body.
*/
tiles map = { /* explicitly initialize members of map here */ };
This should get you running. Of course, the right way to do this is to
define the instance of map in main(), and pass it as a parameter to any
functions that need to read or manipulate it. Keep the header with the
typedef, but omit the extern declaration of map.
.
- References:
- External structs - newbie question
- From: Simon
- External structs - newbie question
- Prev by Date: Re: External structs - newbie question
- Next by Date: Re: External structs - newbie question
- Previous by thread: Re: External structs - newbie question
- Next by thread: Re: External structs - newbie question
- Index(es):
Relevant Pages
|