我有两个 C 源代码文件;一个文件包含如下声明:
volatile unsigned char flag=0;
另一个 C 文件包含一个引用,例如:
extern unsigned char flag;
这是正确且安全的吗?还是应该在引用变量时重复使用 volatile
关键字?即
extern volatile unsigned char flag;
最佳答案
不,这是不正确的。
同一变量的所有声明都需要使用完全相同的类型,volatile
是类型的一部分(extern
不是)
检查 extern
声明的一个好习惯是将它们放在一个头文件中,该头文件也包含在定义所在的编译单元中。然后编译器将检查它们的正确性。
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;
关于c - 引用另一个 C 源文件中声明的 volatile 变量时是否需要 extern 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23813383/