[英]Is it possible to store page_size into an object with static storage duration?
We can extract page_size at runtime via sysconf(_SC_PAGESIZE)
. 我们可以在运行时通过
sysconf(_SC_PAGESIZE)
提取page_size。 My first intention was to put this value on program startup into an object with static storage duration. 我的初衷是将程序启动时的此值放入具有静态存储持续时间的对象中。 So my intention was to declare some
extern
variable in a file scope as follows 所以我的目的是在文件范围内声明一些
extern
变量,如下所示
extern const size_t page_size;
But when I try to define it somewhere else in a file scope as 但是当我尝试在文件范围中的其他地方定义它时
const size_t page_size = (const size_t) sysconf(_SC_PAGESIZE);
it does not compile. 它不会编译。 And that seems to be clear since
6.7.9(p4)
: 从
6.7.9(p4)
开始,这似乎很清楚:
All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.
具有静态或线程存储持续时间的对象的初始化程序中的所有表达式应为常量表达式或字符串文字。
I would not like to call the sysconf(_SC_PAGESIZE)
any time I need a page size. 每当我需要页面大小时,我都不想调用
sysconf(_SC_PAGESIZE)
。 Is there some workaround for that or what is the common solution? 是否有一些解决方法或常见的解决方案?
sysconf(_SC_PAGESIZE)
is a function call. sysconf(_SC_PAGESIZE)
是一个函数调用。 It will always return the same value, but it is still a function call, so it cannot be used to initialize a global variable in C. 它总是返回相同的值,但它仍然是函数调用,因此不能用于初始化C中的全局变量。
If you wanted to avoid calling that function repeatedly, you could declare the global variable as non- const
, and assign its value during application startup. 如果要避免重复调用该函数,可以将全局变量声明为non-
const
,并在应用程序启动期间分配其值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.