Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the extern keyword necessary when referring a volatile variable declared in another C source file?

Tags:

c

extern

volatile

I have two C source code files; one file contains a declaration like the following:

volatile unsigned char flag=0; 

The other C file contains a reference such as:

extern unsigned char flag; 

Is this correct and safe, or should the volatile keyword be repeated whenever referencing the variable? i.e.

extern volatile unsigned char flag; 
like image 315
b20000 Avatar asked May 22 '14 17:05

b20000


1 Answers

No, it's not correct.

All declarations of the same variable need to use the exact same type, and volatile is part of the type (extern is not)

A good practice for checking extern declarations is to put them in a header file that is also included in the compilation unit where the definition exists. Then the compiler will check them for correctness.

Notice what happens if you do that on this example.

prog.c:2:22: error: conflicting type qualifiers for ‘flag’
 extern unsigned char flag; 
                      ^
prog.c:1:24: note: previous definition of ‘flag’ was here
 volatile unsigned char flag=0;
like image 191
Ben Voigt Avatar answered Oct 12 '22 02:10

Ben Voigt