Originally posted by mart_man00
how can i use a structure in multiple source files? this isnt covered any where
I'll give you a quick example. Hopefully this will help you a little bit. Let's say you have 3 files, main.c , extern.c and vector.h lets have a look.
main.c
Code:
#define MAIN_C
#include "vector.h"
int main( void )
{
/* Set the values */
myVector.x = 0.0f;
myVector.y = 50.0f;
myVector.z = 0.0f;
/* Display values */
OutputVector( &myVector );
/* Change our vector externally */
FillVector( );
/* Display values */
OutputVector( &myVector );
return 0;
}
vector.h
Code:
#ifndef VECTOR_H
#define VECTOR_H
/* Simple 3D Vector structure */
struct Vector3D
{
float x;
float y;
float z;
};
/* If we are in the main.c file, we don't use extern .... */
#ifdef MAIN_C
#define GLOBAL
/* If we are in some other file, we want to use extern */
#else
#define GLOBAL extern
#endif
/* Here is our external structure */
GLOBAL struct Vector3D myVector;
/* Prototype the functions */
void FillVector( void );
void OutputVector( struct Vector3D *pV );
#endif /* VECTOR_H */
extern.c
Code:
#include "vector.h"
#include <stdio.h>
/* Fill in external vector with some values */
void FillVector( void )
{
myVector.x = 123.0f;
myVector.y = 444.0f;
myVector.z = 12.0f;
}
/* Output a given vector */
void OutputVector( struct Vector3D *pV )
{
printf( "( %f, %f, %f ) \n", pV->x, pV->y, pV->z );
}
I tryed to comment this code as much as possible. Basically you make a definition for your main.c so that it won't be declared external. However, when you include vector.h other times you don't have MAIN_C defined so it WILL use the extern keyword. Just write back if you have any questions.