Static vs extern in C language

Hello friends!
I was working with a Github library for my new project in raspberry pi, where I encountered the extern keyword. what exactly is an extern keyword? and whats the difference between static and extern keyword? I need some help friends. Thanks in advance.

Static:

Static is used to make a local variable exist throughout the program. If you define a local variable inside a function as static, which will not only make that variable exist throughout the program but also makes the variable available for subsequent function calls. Static is also used with functions so that it is not available to outside current program file.

#include <stdio.h>

void foo()
{
    int a = 10;
    static int b = 10;
    a += 5;
    b += 5;
    printf("a = %d, b = %d\n", a, b);
}

int main()
{
    int i;
    for (i = 0; i < 4; ++i)
    foo();
}

Output:

a = 15, b = 15
a = 15, b = 20
a = 15, b = 25
a = 15, b = 30
a = 15, b = 35

In the above program, the variable a is created every time during the function call but variable b is created only once and remains throughtout the execution of the program.

Extern:

The extern keyword is used to indicate that an identifier is declared here, but is defined elsewhere. In other words, you tell the compiler that some variable will be available, but its memory is allocated somewhere else. It simply helps you to access a variable which is already defined in another file.

main.c

int count;
extern void write_extern();
main()
{
    count=5;
    write_extern();     
}

count.c

extern int count;
void write_extern(void)
 {
     printf("Count: %d\n, count");
 }

Output:

Count: 5 

For more, See

https://medium.com/@shrmoud/static-vs-extern-a79e36f14812

2 Likes

Thanks, @Programmer. You explained it very well.

hello, can you help me assembly programming about?

Ofcourse! Just start a new topic and type your queries. We can help you!!

1 Like