[OCLUG-devel] C and external variables

Christopher Smith x at xman.org
Wed Aug 24 16:36:30 PDT 2005


James Colannino wrote:
> I have a quick question about C and external variables; let's say that
> in one file I have the following:
> 
> typedef struct thing_ {
>    variables;
> } thing;
> 
> Now let's say that I want to declare a variable in another file with
> that external type.  How would I declare it?  Would I have to do another
> typedef in the other file, such as:
> 
> typedef extern thing thing;
> 
> I'm just guessing here, so I know I'm most likely wrong.  Thanks in
> advance.

extern is a modifier on the variable, not the type. Normally what you do
is the type definition is a header that is included by the "other file".

extern just tells you that the storage space for that variable is being
allocated in some other object file (and the linker is going to get
right mad at you if one of the object file's it links doesn't claim
ownership).

So, if I have type defined in "type_defined.h" that I want to have
shared between multiple object files, then any file that uses that type
should '#include "type_defined.h"'. No extern necessary.

If I have a *variable* that is used by multiple objects files, then to
avoid a conflict I need to assign ownership to one of the object files
and have the rest have the variable as an extern. So that probably means
"variable_owned.c" has the variable declared as a global (as opposed to
static), and "other_file.c" has the variable declared as extern (both
will have '#include "type_defined.h"' to get the type definition. The
linker will end up linking together "variable_owned.o" and
"other_file.o" and marry up the storage in variable_owned.o with the
references to the externed variable in other_file.o.

--Chris


More information about the OCLUG-devel mailing list