Connecting Tech Pros Worldwide Forums | Help | Site Map

"extern" for the same file leads to wrong result. bug or feature?

Uenal Mutlu
Guest
 
Posts: n/a
#1: Jul 23 '05
If "extern" is specified for a variable which is already in the same cpp file
then the compiler (VS6) creates a new instance of the var in each thread.
Is this a bug or a feature?
Which is standard conform?

Example:

test.cpp:
int gi = 0;

test.cpp (ie. same file)

thread_func(...)
{
extern int gi;
gi++;
//...
}

thread1 starts and exits. gi now 1 as expected.
thread2 starts and exits. gi now has value 1. Shouldn't it be 2 ?

If the "extern" declaration is not used then gi is 2.
Or, if the "extern" declaration is used and gi is moved to another cpp
then too is gi 2.

What's the correct (std conform) behaviour?


// U.Mutlu



Victor Bazarov
Guest
 
Posts: n/a
#2: Jul 23 '05

re: "extern" for the same file leads to wrong result. bug or feature?


Uenal Mutlu wrote:[color=blue]
> If "extern" is specified for a variable which is already in the same cpp file
> then the compiler (VS6) creates a new instance of the var in each thread.[/color]

Threads are not defined by C++ _language_. You will find more information
in comp.programming.threads or in microsoft.public.vc.language.
[color=blue]
> Is this a bug or a feature?[/color]

Unknown.
[color=blue]
> Which is standard conform?[/color]

Nothing. Or both. Threads are not part of the Standard, so whatever
happens is fine by it.
[color=blue]
>
> Example:
>
> test.cpp:
> int gi = 0;[/color]

This declares an object 'gi' that (by default) has external linkage.
[color=blue]
> test.cpp (ie. same file)
>
> thread_func(...)
> {
> extern int gi;[/color]

This is another declaration of 'gi'. This 'gi' is the same 'gi' as you
declared and defined outside of any function.
[color=blue]
> gi++;
> //...
> }
>
> thread1 starts and exits. gi now 1 as expected.
> thread2 starts and exits. gi now has value 1. Shouldn't it be 2 ?[/color]

Unknown. Threads are not defined by the language.
[color=blue]
> If the "extern" declaration is not used then gi is 2.
> Or, if the "extern" declaration is used and gi is moved to another cpp
> then too is gi 2.
>
> What's the correct (std conform) behaviour?[/color]

Either. Both. Unknown. The use of threads introduces the conditions
that C++ Standard cannot account for.

V
Closed Thread


Similar C / C++ bytes