Blog Archive

Thursday, July 5, 2018

extern keyword in c++

Abstract:
"extern" keyword has two functions:
1)  extern “C” in C++. When some code is put in extern “C” block, the C++ compiler ensures that the function names are unmangled – that the compiler emits a binary file with their names unchanged, as a C compiler would do.


2)  extend life of a variable/function to span the scope of multiple files.

case 1:

Link

// Save file as .cpp and use C++ compiler to compile it
extern "C"
{
    int printf(const char *format,...);
}
 
int main()
{
    printf("GeeksforGeeks");
    return 0;
}

case 2:

Link

Examples:
extern int i;
declares that there is a variable named i of type int, defined somewhere in the program.
extern int j = 0;
defines a variable j with external linkage; the extern keyword is redundant here.
extern void f();
declares that there is a function f taking no arguments and with no return value defined somewhere in the program; extern is redundant, but sometimes considered good style.
extern void f() {;}
defines the function f() declared above; again, the extern keyword is technically redundant here as external linkage is default.
extern const int k = 1;
defines a constant int k with value 1 and external linkage; extern is required because const variables have internal linkage by default.
extern statements are frequently used to allow data to span the scope of multiple files.

No comments:

Post a Comment