tags:

views:

213

answers:

6

I have an include file with 100+ global variables. It's being used in a library, but some programs that I'm linking the lib to also need to access the globals.

The way it was built:

// In one library .c file
#define Extern

// In the programs that use the globals
#define Extern extern

// In the .h file
Extern int a,b,c;

I had a hard time understanding why the original programmer did that so I removed that define Extern stuff. Now I think I understand the thing about TU with the help of stackoverflow: 1, 2, 3.

Now I understand that I should define the global variables in one .c file in the library and use extern in the .h file. The problem is that I don't want to duplicate code.

Should I go back to that #define Extern voodoo?

+3  A: 

It is a bad pattern to have to define Extern in every .c file. Removing it is probably best, but you need to replace this functionality somehow. One approach is that you could use a #define in the .c file that needs to define these globals. This define will signal to the .h to not extern the global variables.

For example: The one library .c file:

#define FOO_LIBRARY_C
#include "foo_library.h"

The other .c files:

#include "foo_library.h"

foo_library.h:

#ifdef FOO_LIBRARY_C
int a,b,c
#else
extern int a,b,c
#endif

or

#ifdef FOO_LIBRARY_C
#define GLOBAL_PREFIX
#else 
#define GLOBAL_PREFIX extern
#endif

GLOBAL_PREFIX int a,b,c

This reduces the need to define the same thing in every single source file (except one) and would help to reduce errors. I also wouldn't call it Extern as that can just cause confusion, as it may or may not be "extern"

Aaron
I disagree that it's a bad pattern:I know this goes against the perceived wisdom of having the externs in .h files, but for this very case I can't think of any other drawbacks than having to write a few extra extern definitions. If you find the need to write tons of them your code is a mess (way too many global variables) and you should in any case ALWAYS think how and where you use them because they can cause very subtle bugs. By using a .h file you are giving yourself a carte blanche to use global variables indisriminantly.
Makis
A: 

I might be missing something, but I see no difference between the #define thingy and just using the extern keyword.

Basically, you have to declare the vars in a .h file and define them in a .c file. Don't consider it code duplication - I think changing the point of view is the best thing you can do here :). You may write more lines of code, but they'll be readable :D.

mingos
I'm willing to be that EXTERN is placed in both the declaration and the header files to make cut and paste of the value jsut that much easier to use and to have a visual que that said var is global scope visible.That said, I shudder about the wonderful abuse this allows everywhere. Oh the days of spaghetti var tracking...
Michael Dorgan
Well, I do that for dll_export and such, but that's because M$VC and gcc do DLLs differently. As for externs, I very much prefer to just have one .h and one .c file for them. Like I said, that's more code, but I like readability. Maybe it's just a personal preference, I dunno. Then again, were I to erite unreadable code, I'd learn to program in Brainf*ck or something similar :)
mingos
That very thing is the reason I do specify global variable names somehow even though I hate the Hungarian notation with a vengeance. Depending on style of the program, I use either the "g" or "g_" prefix for these. It helps inspections more than you could believe.
Makis
+2  A: 

Maybe I'm missing something too, but I ALWAYS use inclusion guards on all the header files I create:

foo.h:

#ifndef FOO_H
#define FOO_H

extern int foo;

#endif

foo.c:

#include "foo.h"

int foo = 0;

bar.c:

#include "foo.h"
#include <stdio.h>
int main(int argc, char** argv)
{
    printf("foo:%d\n",foo);
    return 0;
}
James Morris
I think that this simple strategy won't work with libraries and programs that include the same header file.
Costi
I much prefer this over Aaron's method also listed here. Having the definitions in one file and the declarations in another makes more sense to me, and seems like a much more common pattern.
clintp
People, this won't work. Imagine if I compile the library, and, at a later date, compile a program that includes that .h file. Both will have the globals WITHOUT extern. That's the situation that I'm describing.
Costi
@Costi, foo.c is part of the library, therefor the globals are in the library. your programs will all include foo.h - where the globals are defined extern. the inclusion guards will allow each separately built program to include foo.h once. can you explain how this is broken because i don't see it.
James Morris
My bad, guys. I see now that foo.c has "int foo=0". But I still see a problem with this approach: I have over 100 globals and it's a lot of code duplicated in the .c and .h lib files . With Aaron's solution, they will be declared only in the .h file.
Costi
@Costi: True I guess. From a few quick searches for "c library with global variables" I get the impression that having globals in a library is a bad idea anyway. If I read it correctly, whether two simultaneously running programs share the same set of globals or have their own copies, cannot be relied upon and is OS specific etc.
James Morris
I don't think the data is shared between running processes using the same library. And, anyway we are linking statically to our own lib :)
Costi
@Costi: If this is not your library, it does not matter whether the codes are duplicated. If this is your library, you should really avoid using these many global variables. Even Paul R's solution is much better. James Morris gives the most standard solution.
+1. You shouldn't be using the inclusion of header files to include "code" (versus definitions). I know that the line is blurry here, but the idea of flipping the extern keyword off to effectively have the header function as the definition works but is just a byproduct of managing "too many" globals anyways (I know this is subjective, but I'm explaining why this pattern isn't so common in the wild.)
quixoto
+2  A: 

The trick here is that the .h file is being used in two different ways - it's being used as a normal .h file where all the globals are declared extern and it's also being used to define the globals themselves (with no extern). This is an ugly hack but you can understand why someone felt it necessary if you have a large number of globals (a sure sign of very bad software design !).

Anyway, there is a somewhat more elegant solution - you can put all your globals in a single global struct, e.g.

//
// globals.h
//

typedef struct {
    int a;
    int b;
    // ...
    int z;
} Globals;

extern Globals globals; // declaration

-

//
// globals.c
//

#include "globals.h"

Globals globals; // definition

-

Then when you need to refer to a global it's e.g. globals.a instead of just a, which might seem like an inconvenience but this is arguably clearer and more manageable than just having naked globals scattered throughout the code.

Paul R
Certainly is :-)
James Morris
You're right, and putting those globals in some structures is a TODO. It's even possible to give them some meaningful names.
Costi
A: 

While this can be annoying at first it does help you avoid having to type thing twice or forgetting to include something in a .c file at all. I've seen:

#define FOO_C_

#include "foo.h"
#include "bar.h"

int foo_doit(int a, int b, int c) {
...
}

with foo.h being:

#ifndef FOO_H_
#define FOO_H_

#ifdef FOO_C_
#define GLOBAL
#define DECLARE( type, name, value) type name = value
#else
#define GLOBAL extern
#define DECLARE( type, name, value) extern type name;
#endif

GLOBAL int foo_doit(int a, int b, int c);
GLOBAL int foo_it; // uninitialized global variable
DECLARE(char, that[], "that");

// and sometimes using:
#ifdef FOO_C_
char word[] = letters;
#else
extern char word[];
#endif


#endif // FOO_H_
nategoose
A: 

As a rule of thumb - don't use global variables. Sometimes you need to use static variables in file but it is best to try to avoid them at all:

  • You cannot unit test properly code which contains global variables
  • There is no clean separation between modules which can cause problems with isolation of errors
  • It is usually not thread safe. You have to wrap them with mutexes etc. if you want to use threads (tends to be better and better idea as we get more and more cores) you can run into troubles with writeable shared state.

Sometimes in C you cannot avoid them (especially in code inherited by someone) but best is to keep them out.

As for the declaration - it might be helpful in such case:

// globals.h

#ifndef GLOBALS_H
#define GLOBALS_H

#ifndef EXTERN
#define EXTERN extern
#endif

EXTERN int i;
#endif

// globals.c
#define EXTERN
#include "globals.h"
Maciej Piechotka