Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am very very sorry. I didn't know my incomplete code attachment would create such a mess. I am very glad to see so many sincere helps.

This code will compile:

int myadd(int, int);
static int main_stat = 5;

int main()
{
    int i, j;
    main_stat = 13;
    j = myadd(-1,7);
    i = main_stat;

    cout << j << i;     //  3  and 13
    return 0;

}

myadd.cpp

extern int main_stat = -3;
int myadd(int x,int y)
{
    int t = main_stat;
    t = x + y;
    y = t +main_stat;
    return y;    // will return 3
}

See I defined and extern linking main_stat. Why is that legal? I thought you could only link and not define.

Is storage allocated in the stack frame of myadd function call? Global static are allocated on heap, I believe, right?


EDIT

I am sorry, but I think this time I will narrow down my questions:

From C++ Primer 4ed

An extern declaration may include an initializer (when combined becomes definition) only if it appears outside a function.

I am clear about one-definition rule.

Q1. Which copy of main_stat does myadd(int,int) uses when it is called? The same copy as the main has, but with a different value (which I can test) ? Or does each function has its own static global copy?

Q2. Is memory allocated on the heap for these global static variables? I know many things are up to implementation, but isn't heap used for static variables?

Q3. I know the followings two are valid

extern int x;    // means int x is defined elsewhere
extern int x = 3;  // declared and defined 

Why do we want the second one if we can just declare a static global variable within the namespace of myadd ? How does it make things clear like aschepler said?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
467 views
Welcome To Ask or Share your Answers For Others

1 Answer

All variable declarations with an initializer are also definitions; that's an overriding rule. Regardless of extern. There are even cases where you need an extern on a definition: you can only instantiate a template using a variable which has external linkage. And const variables have internal linkage by default, so you need something like:

extern int const i = 42;

if you want to use it to instantiate a template<int const*>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...