Re: keyword extern

From: Emmanuel Delahaye (emdelYOURBRA_at_noos.fr)
Date: 06/26/04


Date: 26 Jun 2004 08:11:28 GMT

In 'comp.lang.c', yasheshb@gmail.com (Yashesh Bhatia) wrote:

>> Or is it better to write
>>
>> extern int a;
>>
>> in all the files except where it's originally defined?
>>
> Well, my preferred way would be to declare it in all the .c files that
> need the extern variable rather than put the extern declaration in the
> header file and include the header file in the c files. The reason
> being.
>
> - If the variable was used by all c files, it would be better to make
> it a global variable in the .h file.

No. A header is certainely not the place for an object definition for an
obvious reason. If you include the header in more than one compile unit, you
will have more than one definition of the object with the same name. This is
the kind of situation a linker can't handle, except by an error message.
 
> - Keeping the extern declaration in the .c file instead of the .h
> file will make it easier for other .c files that dont need the extern
> variable but need other declarations from the .h file to include it.

The maintainers of such a code will doom you for ever. Please don't do that.
The OP's first proposal was nearly the good one. Please read my previous
answer to learn why.

-- 
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/


Relevant Pages

  • Re: confused about extern use
    ... going to achieve by declaring it as extern in the header file a.h. ... composed on one or more compilation units. ... Essentially you *declare* the type wherever it is ...
    (comp.lang.c)
  • Re: keyword extern
    ... > declared multiple times using extern in all the files file2.c ... NEVER, ever, define a variable in a header file. ... declare it with the "extern" qualifier in the header file for the ... misuse. ...
    (comp.lang.c)
  • Re: How to declare functions in so to be accessable to applications
    ... >> But the application tells my, that it didn't find the entry point ... > Your header file that the application uses, ... > prototype normally, not as an extern. ... When you declare it extern, ...
    (comp.unix.programmer)
  • Re: error LNK2005
    ... variables in the header file; consequently, each module which includes it gets a new, ... Declare the variable once, in the .cpp file associated with the .h file. ... extern in the header file. ... complain but all the other files claim that my arrays are already ...
    (microsoft.public.vc.mfc)
  • Re: const and extern...
    ... extern float bar; ... a declaration), but if you merely declare it, you do not define it. ... or the translation unit ends. ... an actual definition with an initializer of: ...
    (comp.lang.c)