声明为常量,但定义为非常量,C

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

回答

在头文件中声明变量的唯一逻辑方法是将它们声明为 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


以上是声明为常量,但定义为非常量,C的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>