How to define external variables in C++

In C++, external variables can be defined by declaring and defining them outside functions or classes. External variables can be defined in the global scope or within a namespace.

  1. Define external variables in the global scope.
int globalVariable; // 在全局作用域中定义外部变量

int main() {
    // 使用外部变量globalVariable
    globalVariable = 10;
    return 0;
}
  1. Define external variables in the namespace.
namespace MyNamespace {
    int externalVariable; // 在命名空间中定义外部变量
}

int main() {
    // 使用外部变量MyNamespace::externalVariable
    MyNamespace::externalVariable = 20;
    return 0;
}

Before using external variables, they must be declared to inform the compiler of their existence. For instance, when using a global variable in a function, the variable can be declared using the extern keyword within the function.

extern int globalVariable; // 声明全局变量

int main() {
    // 使用外部变量globalVariable
    globalVariable = 10;
    return 0;
}

If the definition of an external variable is not provided but only declared, the compiler will search for the definition of that variable at the linking stage.

Leave a Reply 0

Your email address will not be published. Required fields are marked *