简体   繁体   中英

reinitialize a global variable that is already defined in other source file

I'm new to C, just a question on global variable, below is the code that uses the header file as recommended:

//test.h

extern int globalVariable;
//test.c

#include "test.h"

int globalVariable = 2020;
//main.c

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

int main()
{
   printf("Value is %d", globalVariable);
}

so it works well and the print output is 2020.

But if I change the main.c as:

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

int globalVariable;

int main()
{
   printf("Value is %d", globalVariable);
}

it still compile and the output is still 2020. Below is my question:

Q1-When I add int globalVariable; in main.c, isn't that it re-initialize the globalVariable to 0 becuase int globalVariable; is the same as int globalVariable = 0; . So why the output is still 2020 rather than 0?

Q2- globalVariable is already defined in test.c , and I re-define(reinitialize) it to 0, should it be a compile error since C doesn't allow multiple definition, so why the program still compile?

This declaration at file scope:

int globalVariable;

Is a tentative definition . It has no initializer and is not static . GCC can "fold" tentative definitions together from multiple translation units into a single identifier. This is not specified by the standard but is an extension supported by GCC.

In this case the tentative definition in main.c gets rolled into the the complete definition in test.c and initialized with the given value. If you were to use an initializer in main.c as well, then you would get a multiple definition error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM