天天看點

A story of declaration and defintion (C++)

"""

To support separate compilation, c++ distinguishes between declarations and definitions. A declaration makes a name known to the program. A file that wants to use a name defined elsewhere includes delcaration for that name. A definition creates the asociated entity.

A variable declaration specifies the type and name of a avariable. A varaiable definition is a declaration. In addition to specifying the name and type, a definition also allocates storage and may provide the variable with an initial vale.

To obtain a declaration that is not also a definition, we add theexternkeyword and may not provide an explicit initializer.

extern int i; // delcare but does not define i

int j;  // delcares and defines j

Any delcaration that includes an explicit initializer is a definnition, wecanprovide an initializer on a variable defined as extern, but doing so overrides the extern . An extern that has an initializer is a definition:

extern double pi = 3.1416; // definition;

It is an error to provide an initializer on an extern inside a funtion.

Note: variables must be defined exactly once but can be declared many times.

The distinction between a declaration and a definition may seem obscure at this point but is actually important. To use a variable in more than once file requires declarations that are separate from the variable's definition. To use the same variable in multiple files, we must define that varaible in one-and only one-file. other files that use that variable must delcare-but not define -that variable.

"""

One variable can be called by another files, the shared-variable, if we need to use it, just declare it in the header of file.Declaration and definition are not the same meaning in C++. definition means you should give a value to a variable and its type. "extern" is a key word. if a varaible are declared by the word. it means we can call it in the project(another files can share it), the shared-variables.

"It is an error to provide an initializer on an extern inside a function"

#include <iostream>

using namespace std;

extern int i = 120;

int main()
{
    extern int i = 99; // error: 'i' has both 'extern' and initializer
    cout << i << endl;
    return 0;
}
           

Change the statement : extern int i = 99, extern int i.

What happend?

print the value of "i" -- 120 in the console.

繼續閱讀