如果你有一个在初始化代码中设置后实际上是常量的变量,是否可以在头文件中声明它
const
?例如:
extdef.h:
#ifndef DEFINING_X
extern const int x;
#endif
void init_x();
extdef.c:
#define DEFINING_X
#include "xdef.h"
int x;
void init_x() { x = 42; }
main.c:
#include <stdio.h>
#include "xdef.h"
int main(int argc, char *argv[]) {
init_x();
printf("x is %d\n", x);
}
显然这并不完全安全,因为它依赖于在访问
init_x
之前调用 x
,但如果我保证这一点,我可以相信这是明确定义的吗?当我测试它时,它似乎以预期的方式工作。
请注意,我只使用纯 C,而不是 C++。
我认为是的,如果在初始化代码中设置后实际上是一个常量,则可以在头文件中将变量声明为 const。您的代码非常正确。
您可以使用以下代码进行测试:
#include <stdio.h>
#include "xdef.h"
int main(int argc, char *argv[]) {
printf("x is %d before calling init_x()\n", x);
init_x();
printf("x is %d after calling init_x()\n", x);
return 0;
}
输出:
x is 0 before calling init_x()
x is 42 after calling init_x()