Home > Mobile >  Can extern make a function variable a global variable?
Can extern make a function variable a global variable?

Time:05-07

As I understood extern makes a variable --> global variable, so it means we can also make variable of another function a global variable?

#include <stdio.h>

extern char* name;

void namePrint();

int main(void) {
    printf("%s\n", name);
    namePrint();
}

void namePrint() {
    printf("%s", name);
    char* name = "Satyam";
}

CodePudding user response:

You understood extern wrong. It's not about making symbols "global". Tells tells the compiler about the existence of a symbol that has been created somewhere else, that is outside (which is literally what the word "extern" means) from the current translation unit.

It's kind of declaring a function before using it. Using extern in function declarations is allowed:

// someheader.h
extern void foo(void);

In fact semantically the usual functions are declared, that is without the use of extern is just a shorthand for doing it with.

CodePudding user response:

By the term "global variable" C programmers mean variables (with external or internal linkage) having file scope.

Variables declared within functions are local variables and invisible outside the function scope where they are declared.

You could declare within a function a variable that will refer to a variable in file scope using the storage class specifier extern. For example

char* name = "Satyam";

void namePrint();

int main(void) {
    printf("%s\n", name);
    namePrint();
}

void namePrint() {
    extern char* name;
    printf("%s\n", name);
}

Here within the function namePring the declared variable name refers to the global variable name declared in the file scope. That is it denotes the global variable name.

Or more meaningful example

char* name = "Satyam";

void namePrint();

int main(void) {
    printf("%s\n", name);
    namePrint();
}

void namePrint() {
    char *name = "Programmer";
    printf( "%s ", name );
    {
        extern char* name;
        printf("%s\n", name);
    }
}

CodePudding user response:

In addition to the other answers:

As your code is now, it compiles, but doesn't link.

By extern char* name; you are telling the compiler that somewhere a global variable name exists. The compiler is fine with this.

This function:

void namePrint() {
    printf("%s", name);
    char* name = "Satyam";
}

uses this global variable in the printf() call. The definition of the local variable name in the following line is another variable with the same name. It would "shadow" the global variable, if there were some code accessing name afterwards (it isn't).

Because you never define the global variable name, the linker cannot resolve the references.

  • Related