首页 > 解决方案 > 声明为 const,但定义为非常量,C

问题描述

在我的标题中声明一个 const 变量是否有效,但将其定义为非常量变量以供内部使用?

标签: c

解决方案


在头文件中声明变量的唯一合乎逻辑的方法是将它们声明为extern

由于#include仅将头文件的文本插入源代码文件(https://godbolt.org/z/nor8nz),您可以简单地在单个源文件中测试您的想法:

extern const int x;

int x;

https://godbolt.org/z/PWEzGM

你会得到错误:

1
ARM gcc 8.2
- 347ms

<source>:4:5: error: conflicting type qualifiers for 'x'
 int x;
     ^
<source>:2:18: note: previous declaration of 'x' was here
 extern const int x;
                  ^
Compiler returned: 1

推荐阅读