Thursday, July 30, 2009

C prog multiple files?

These are my files. I'm wondering is this the right way to do it.





/* game.h */





#ifndef GAME_


#define GAME_





extern void game (void);


extern void enemyFunc (void);


extern int enemyPosX;





#endif





/* game.c */





#include "game.h"





int enemyPosX;





void game (void)


{


enemyFunc();


}








/* enemy.c */





#include "game.h"





void enemyFunc (void)


{


enemyPosX -= 4;


}








It works but if i take the





extern int enemyPosX;





out of game.h, it still work?

C prog multiple files?
When you take "extern int enemyPosX;" out of game.h, you should indeed get a compiler error when you try to recompile enemy.c, which it sounds like you were expecting. Is there any chance that you didn't actually recompile enemy.c? If you were to use an object file that was created from the original, it would still be able to link.





I suggest you remove any object files and try to compile again.





If it still compiles clean, then what compiler are you using and what commands are you using to compile?





REGARDING YOUR FOLLOWUP, your general structure is correct. It is good form to create a .h file that contains function declarations for the function that will be shared from the .c file to other .c files. You do not actually have to use extern in front of function declarations, as that is assumed, but you would use extern in front of variables that you declare.





You should really try to keep global variables to an absolute minimum, and pass values between functions instead. This will help avoid introducing weird side-effects that are hard to track down. If you have a lot of variables that you need to pass around, you may want to consider creating one or more struct's so you can pass a single pointer to a struct that contains the related variables.





http://www.cs.cf.ac.uk/Dave/C/node35.htm... has some good ideas to follow for creating large proejcts.





http://publications.gbdirect.co.uk/c_boo... covers these details as well, and from there, follow through to chapter 8 for really gory details to consider.

aster

No comments:

Post a Comment