Rajeshwar
Rajeshwar

Reputation: 11661

Does the value of a static int change in this case

I currently have a header file that is included by multiple header and source files. The header file looks something like this

File:External.h
#ifndef EXTERNAL_H
#define EXTERNAL_H

#include "memory"

static int pid=-1;

#endif // EXTERNAL_H

This is a simplification of my current scenario just to check if I might be wrong.Now suppose I have two classes foo and bar. Here is the behaviour that I have noticed.

#include "External.h"
void foo::someMethod()
{
   pid =13; //Change the value of pid;
   bar_ptr = new bar();
}

//bar constrcutor
#include "External.h"
bar::bar()
{
   int a = pid;  //The value of a is -1 wasnt it suppose to be 13
}

Wasnt the value of a suppose to be 13 especially since its an open variable (not a struct or class) of static type.?

Upvotes: 0

Views: 47

Answers (1)

Buddy
Buddy

Reputation: 11038

That is because each file is including the header, and thus each compilation unit (roughly source file) will have this definition inside of it:

static int pid=-1;

Thus they each have their own copy.

Really you should do something like:

External.h

// The declaration, so that people can access it
extern int pid;

External.c

// The actual implementation
int pid = -1;

Upvotes: 4

Related Questions