Sam Charette wrote in message <10292@palm-dev-forum>...
>
>Well, all of the globals were in only one file, but it was the extern
keyword I was fishing for.  I do have a question tho... many
>people have said nearly the same as you, but you and someone else said it
slightly differently.
>
>What I ended up doing was this:
>
><headerfile>.h
>
>#ifndef MYHEADER
>#define MYHEADER
>int     myVariable;
>#endif
>
><end headerfile>
>
><any module file>.c
>
>#include "<headerfile>.h"
>
>extern int    myVariable;
>
><end module file>
>
>You seem to have the extern in the header xyzzy.h, a redeclaration in
xyzzy.c and nothing in plugh.c.  You are not the only one to
>have the extern in the header instead of the module files... is there
something more subtle about the use of extern that I am
>missing?
>

I am surprised that would work.   Remember, the #include is just
an instruction to the compiler that says "put the text from this file
in here".  Which means that each of your .c files that included your
.h file has the declaration of "int myVariable;" in it.  Your linker should
probably be reporting multiply defined symbols.

"int myVar;" (w/o the extern) tells the compiler "allocate room for
an int, and tag it w/ the name "myVar" for future reference".

"extern int myVar;" tells the compiler "we're expecting somebody
else to supply an int tagged with the name "myVar"".

The linker joins up all the modules expecting that int with the -one-
module that took responsibility for allocating room for it.

Therefore you need to have code that results in one, and only
one, .c file contining the "int myVar;" declaration (w/o extern).

One way to do this is as I described: the header contains
the "extern" -- essentially similar to a function prototype but
for variables -- and in one module you declare the variable
itself.

The other way to do this is a bit tricker, and difficult for some
people to follow.  Put these lines in your .h file:

#ifdef MASTER
#define MAGIC
#else
#define MAGIC extern
#endif

MAGIC int myVar;

Then in one of your .c files, before including the .h
file, put the line:

#define MASTER

The file that has this line takes responsibility for
declaring the variables.  The symbol MAGIC resolves
to nothing and the variables are declared.  For all other
files (that do not define MASTER) the symbol MAGIC
expands to "extern", and they can use the variable but
do not end up allocating space for it.

This is a cute trick to play with the preprocessor, but
I really think the way I described before (.h file containing
only "extern" declarations & one .c file containing the
real one) is more straightforward, and easier to follow
for most people.



--
-Richard M. Hartman
[EMAIL PROTECTED]

186,000 mi/sec: not just a good idea, it's the LAW!



-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palmos.com/dev/tech/support/forums/

Reply via email to