我有一些全局变量需要在多源文件上共享。我已阅读How do I share variables between different .c files?并执行以下操作:
fileA.h
:
extern int a;
fileA.c
:
int a;
// using a variable here
一切都编译良好并且工作正常。但因为我是在多线程环境下编程,所以我在每个变量之前添加了 volatile
关键字。所以现在是:
fileA.h
:
extern volatile int a;
fileA.c
:
int a;
// using a variable here
但是当我使用这种方式时,编译时遇到错误:
error: conflicting type qualifiers for ‘a’ in file included from fileA.c:4:0:
请帮我解释一下原因,以及如何解决这个问题?在这种情况下我们应该使用 volatile
吗?
最佳答案
变量的任何声明都应与其实际定义一致。因此,如果 extern volatile int a;
的包含文件中的声明应该在实际定义该变量的文件中具有关联的 volatile int a;
。
另请参阅这篇文章 How to use C's volatile keyword包括有关多线程应用程序的一些信息。
请注意,对于多线程应用程序,您可能需要对共享变量使用某种锁定或其他互斥机制。请参阅Why is volatile not considered useful in multi-threaded C or C++ programs
volatile 关键字的主要作用是通知编译器变量可能会因当前范围之外的某些操作而更改,因此它会影响编译器生成机器代码的方式。
请参阅这篇简短的文章 Compiler optimization and the volatile keyword .
请参阅多布斯博士的这篇文章 volatile: The Multithreaded Programmer's Best Friend
关于c - 多源文件中的 extern volatile ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23038706/