Public Group

# Organising C source files.

This topic is 2941 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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
maingame.c
highscores.c

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.

##### Share on other sites
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.

##### Share on other sites
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.

##### Share on other sites
Moved to For Beginners.

##### Share on other sites

Thanks CE - a great explanation, very helpful indeed.

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

All the best!

1. 1
2. 2
frob
12
3. 3
4. 4
5. 5
Rutin
10

• 13
• 14
• 65
• 14
• 15
• ### Forum Statistics

• Total Topics
632130
• Total Posts
3004283

×