Re: External structs - newbie question
- From: "Simon" <yaroguelike@xxxxxxxxxxxxxx>
- Date: 10 Nov 2006 12:19:56 -0800
Simon Biber wrote:
Declaring it in a header file is the right way to go. If you put the
keyword extern before the declaration, it will not be a problem
declaring it twice. Just make sure that you don't put an initialiser on it.
You should declare it extern in the header, which is included in both
files. But you should also define it (without extern), in one of the
files only.
Below I've given an example layout for your header file. Note each of
the things in it: include guards, global constants, type definitions,
global variable declarations and function declarations.
/* map.h */
/* Include guards */
#ifndef H_MAP
#define H_MAP
/* Global constants */
#define MAP_HEIGHT 30
#define MAP_WIDTH 30
/* Type definitions */
struct tile
{
int terrain;
};
/* Global variable declarations */
extern struct tile map[MAP_HEIGHT][MAP_WIDTH];
/* Global function declarations */
void init_map(void);
#endif
/* csd.c */
#include "map.h"
/* Define map in only one of the files */
struct tile map[MAP_HEIGHT][MAP_WIDTH];
int main(void)
{
init_map();
return 0;
}
/* org.c */
#include "map.h"
void init_map(void)
{
int i, j;
for(i = 0; i < MAP_HEIGHT; i++)
{
for(j = 0; j < MAP_WIDTH; j++)
{
map[i][j].terrain = 1;
}
}
}
/* Example compile process for gcc */
gcc -ansi -pedantic -Wall -W -O2 -c csd.c
gcc -ansi -pedantic -Wall -W -O2 -c org.c
gcc -ansi -pedantic -Wall -W -O2 csd.o org.o -o csd
./csd
--
Simon.
I followed these instructions quite precisely, but the result was a bit
confusing. When I compile I now get a series of errors throughout
main() which say "invalid use of undefined type 'struct tiles'".
I also get an interesting error at the line in csd.c where I define map
(struct tile map[MAP_HEIGHT][MAP_WIDTH];) which says "storage size of
'map' isn't known".
There must be something obvious I'm missing...
Simon
.
- Follow-Ups:
- Re: External structs - newbie question
- From: Simon
- Re: External structs - newbie question
- References:
- External structs - newbie question
- From: Simon
- Re: External structs - newbie question
- From: Simon Biber
- External structs - newbie question
- Prev by Date: Re: 2D array of structures
- Next by Date: Re: How to store a 13 digit number in c ?
- Previous by thread: Re: External structs - newbie question
- Next by thread: Re: External structs - newbie question
- Index(es):
Relevant Pages
|
|