可以从编译时未知的其他地方修改 const 变量吗

标签 c linker compiler-construction constants

如果 const 是编译时构造,则意味着只有编译器才能确保,例如,如果将变量声明为 const,则该变量是只读的,并且不会尝试由其余代码对其进行修改正在编译?

如果 const 变量是我们代码中的全局变量,并且我们的代码在运行时链接到试图写入它的动态库,该怎么办? ,或者如果 ISR 尝试更新它,但它不在我们编译的代码中?

我相信编译器可以将 const 变量标记为加载到只读数据部分,这将防止变量发生任何更改,但如果不这样做怎么办?

谢谢

最佳答案

the compiler will ensure that for example if a variable is declared as const, this variable is read only and it is not attempted to be modified by the rest of the code being compiled?

是的,据编译器所知。如果您的代码尝试写入 const 限定变量,您将收到编译器错误。如果您通过放弃 const 限定符等方式来避免类型正确性,那么所有的赌注都会失败。

What about if a const variable is a global variable in our code, and our code links to a dynamic library at run time which attempts to write to it? , or if an ISR attempts to update it, which was not in our compiled code?

那么它不应该被 const 限定,否则编译器将做出奇怪的假设并生成不正确的代码。

但是,在某些情况下,const 变量可能会从外部世界更新 - 它可能是只读硬件寄存器或 EEPROM 存储单元等。

为了防止编译器在这种特殊情况下做出奇怪的假设,您可以组合 constvolatile。因此,所有可能从外部源(例如硬件或 ISR)更新的变量都应始终声明为 volatile

关于可以从编译时未知的其他地方修改 const 变量吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48283471/

相关文章:

c - 在可下载内核模块中调用代码时 undefined reference

c++ - C++ 命名空间中的内联函数

linker - 使用 CMake 链接静态库

c++ - 如果字符在引号之间则不匹配(AKA 具有编程字符串模式)

c - DFS算法迷宫生成器

我可以在具有多个值的 C 上使用 switch case 吗?

assembly - 计算汇编语言指令的成本

c++ - Visual Studio 2010,超线程处理器的最大并发 C++ 编译

c - 是否有任何库来解析 C 中的 TCP/IP/UDP header

c - malloc指针导致内存泄漏?