简体   繁体   English

是否可以将page_size存储到具有静态存储持续时间的对象中?

[英]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.

相关问题 PAGE_SIZE未声明的C. - PAGE_SIZE undeclared C c - *(void **)&(int [2]){0,PAGE_SIZE}; 含义? - c - *(void **) &(int[2]){0,PAGE_SIZE}; meaning? 无限调用sbrk(PAGE_SIZE)的结果 - Result of infinite call to sbrk(PAGE_SIZE) vmalloc() 返回的地址是 PAGE_SIZE 的倍数吗? - Is the address returned by vmalloc() a multiple of PAGE_SIZE? Static 字符串的存储时长 - Static storage duration for a string __attribute __((____ aligned __(PAGE_SIZE)))是什么意思? - what does it mean by __attribute__((__aligned__(PAGE_SIZE)))? 为什么 memory 管理器使用 (size + PAGE_SIZE-1) / PAGE_SIZE 来计算要分配的页数? - Why do memory managers use (size + PAGE_SIZE-1) / PAGE_SIZE to calculate the number of pages to allocate? 为什么 GCC/Clang 会接受 const 限定对象作为具有静态存储持续时间的对象的初始值设定项? - Why would GCC/Clang accept const qualified object as initializer for object with static storage duration? pAddress和〜(PAGE_SIZE-1)获取页面基址的技巧是什么? - What is the trick in pAddress & ~(PAGE_SIZE - 1) to get the page's base address 从多个库动态加载时的静态存储持续时间对象唯一性保证 - Static-storage-duration object uniquness guaranties when dynamically loaded from multiple libraries
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM