Organising C source files.

Started by
3 comments, last by FlyingSolo 13 years, 8 months ago
Hi, none of the books I have nor an hour spent googling have found a satisfactory answer to this - I hope someone here can help!

Let's say I have a program consisting of a single large source file but I wish to split the project into smaller files each containing related functions. Using a game as an example I might want something like:

intro.c
loadfiles.c
maingame.c
highscores.c

where each file has access to global variables defined in.... ?

The question is, how do I make the large number of neccesary global variables available to all source files?

I've seen programs that declare variables in header files (I'm told that is bad) and I've seen a setup where the main .c file declares the variables and then a header re-declares them as extern. Painful duplication!

So... can someone please put me out of my misery and explain the correct way to do this?

Many thanks.
Advertisement
Maybe you already know this: Organizing C/C++ source files.

Anyway, the extern thing is basically the only way to do globals. The duplication really shouldn't be too bad. It's no more than the name duplication you'd already have to do for function names declared in .h's and implemented in .c's.

First of all, you want to minimise the "large number of necessary global variables". Go through each one and ask yourself is it really necessary for this to be global? Could it be passed as a parameter instead?

Next, unfortunately you're going to have put up with the "painful duplication". Declaring variables as extern in a header and defining them in the appropriate .c file is the correct C way of doing this.

By the way, there are varying degrees of "globalness". You may have some variables that are truly global, (although again, is it really necessary for this to be global?) but even if a variable is in the global scope, it should still be declared in the correct header.

So expanding from your example, let's say that for some reason the game title has to be global. You could declare
extern char* GameTitle;

in intro.h and define
char* GameTitle = "My Super Game";
in intro.c

That way only files that need to use GameTitle can include intro.h and anything that doesn't need to know about it can remain blissfully ignorant.

OT: unless you're working on a severely resource constrained environment, do yourself a favour and ditch C.

if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
Moved to For Beginners.

Thanks CE - a great explanation, very helpful indeed.

Apologies for not thanking you sooner - Other problems at this end.

All the best!

This topic is closed to new replies.

Advertisement