
problems using one header file for multiple source files
Groovy hepcat Jason Stratos Papadopoulos was jivin' on 15 Dec 1997
05:24:00 GMT in comp.lang.c.
problems using one header file for multiple source files's a cool
scene! Dig it!
Quote:
>Hello. Oh, I just know I'm going to look like an idiot for
>asking such a stupid question, but I have a single .h file
>that includes other files, makes global variables, and sets
When you say "makes global variables", what exactly do you mean? If
you mean declares them, then it should be fine. If, OTOH, you mean
defines them, then you've got problems!
Judging by the fact that you've got problems, and the specific
nature of those problems, I'd say it's the latter.
Quote:
>up structures. If I write all my functions into one .c file
>and include said .h file, everything works fine. If I split
>my C code over several files, including the .h file in each
>causes numerous compilation errors having to do with variables
>being declared over again.
Uh huh. Common error. But they're *defined* over again, not just
declared over again.
Quote:
>What the heck's wrong?! For the record, the .h file does have
You're defining variables within the header, such as:
int foo;
float bar;
The above lines define two variables with external linkage (since
they're outside of any function definitions). They set asside space
for the variables. If the header is included in multiple modules, it
gets compiled multiple times, and the variables are defined multiple
times. When the linker tries to link the modules together, it
encounters multiple definitions of the same variables, and spits out
an error message.
What you should be doing is *declaring* them, not defining them. You
must also define them in one .c file once.
How to declare a variable in a header (using the same variables used
in the example above):
extern int foo;
extern float bar;
It's as simple as that. Simply prepend extern to the variable
declarations, which tells the compiler the variables are defined in
another source file.
An extern declaration can appear in the same translation unit (even
the same file) as the definition, though. So this is valid:
/* myfile.h */
extern int foo;
extern float bar;
/* end */
/* myfile.c */
#include "myfile.h"
int foo;
float bar;
/* end */
----- Dig the EVEN NEWER, MORE IMPROVED news sig!! -----
-------------- Shaggy was here! ---------------
http://aardvark.apana.org.au/~phaywood/
============= Ain't I'm a dawg!! ==============