"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 itextern "C"{ int printf(const char *format,...);}int main(){ printf("GeeksforGeeks"); return 0;} |
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
externkeyword 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;
externis redundant, but sometimes considered good style.
extern void f() {;}
- defines the function f() declared above; again, the
externkeyword 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