Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What a C static variable in file scope means?

I have three files to demonstrate the use of static variable in file scope. Variable is declared as extern in file2.h, initialized in file2.c. I am declaring another variable with same name in main.c as static to test for static global scope. But I get the error message "main.c|6|error: static declaration of 'var1' follows non-static declaration.

Could someone explain me the usage of static for file scope?

If I do not include file2.h in main.c, I do not get any problem. But what if I need to use some functions of other files in main.c but still want to keep the variable scope to this file only?

main.c

#include <stdio.h>
#include "file2.h"


static int var1;

    int main()
    {
        printf("value of staticVar1 = %d\n",var1);
        func1();
        printf("value of staticVar1 after function call= %d\n",var1);
        return 0;
    }

file2.h

#ifndef _FILE2_H
#define _FILE2_H
#include <stdio.h>

extern int var1;

int func1(void);

#endif // _FILE2_H

file2.c

#include <stdio.h>
#include "file2.h"

int var1=3;

int func1(void)
{
    printf("value of staticVar1 inside the function = %d\n",var1);
    return(0);
}
like image 300
Jon Wheelock Avatar asked Jan 08 '23 10:01

Jon Wheelock


1 Answers

An object declared at file scope has either external or internal linkage, it cannot have both linkages:

extern int var1;  // declare var1 an int with external linkage
int var1 = 3;     // declare and define var1 with external linkage
static int var1;  // declare and define var1 an int with internal linkage
                  // -> ERROR var1 is redeclared with different linkage

You use static specifier if you want an object with visibility limited to the source file in which you declared it.

like image 118
ouah Avatar answered Jan 17 '23 05:01

ouah