Peter Ammon wrote:
I would like to share a variable between two functions defined in two
separate source files; no other functions will need the global variable
so I'd prefer to not give it file scope. Thus, I want a variable with
local scope, external linkage, and static storage.
I believe I can do this for the file that does not define the variable
by declaring it inside a function. Can I also avoid giving it file
scope in the file that does define the variable?
/* File 1 */
void function1(void) {
/* How do I make myGlobal have static storage,
* and external linkage?
*/
int myGlobal;
}
/* File 2 */
void function2(void) {
/* This does what I think it does, right? */
extern int myGlobal;
}
C's linkage scheme is not fancy enough to do what
you desire. All identifiers with external linkage are
(potentially) visible to all parts of the program, and
there's no notion of a "package-private" linkage.
In the code you've shown, the identifier `myGlobal'
refers to two different objects:
- In function1(), it refers to an `auto' variable.
The identifier has no linkage, neither external
nor internal. You could change the storage class
by adding the `static' or `register' (or even
`typedef'!) keyword, but it wouldn't alter the
fact that this `myGlobal' has nothing at all to
do with any other `myGlobal' identifier that might
be lying around in your program.
- In function2(), `myGlobal' has external linkage.
When the various translation units are combined
into a program, this `myGlobal' and any others
that also have external linkage will be made to
refer to one object. Exactly one translation unit
must provide an actual definition of the object,
at file scope and without the `static' keyword --
and if that definition is a function or is a data
object that isn't `int', you've got trouble.
"You can't always get what you want." -- J&R
--
Er*********@sun.com