简体   繁体   English

Linux _SC_PHYS_PAGES 不适用于 Mac OS X

[英]Linux _SC_PHYS_PAGES not working on Mac OS X

I am trying to compile a project on Mac OS that doesn't make any problems under Linux.我正在尝试在 Mac OS 上编译一个在 Linux 下不会出现任何问题的项目。 I am using GCC on both operating systems.我在两个操作系统上都使用 GCC。 Besides other problems that I managed to fix, I get the following error when trying to compile on OSX:除了我设法修复的其他问题外,尝试在 OSX 上编译时出现以下错误:

error: ‘_SC_PHYS_PAGES’ was not declared in this scope
     long pages = sysconf(_SC_PHYS_PAGES);
                      ^

unistd.h is included in the file where this error occurs. unistd.h包含在发生此错误的文件中。

How can I fix this in a way that the code still compiles under Linux?如何以代码在 Linux 下仍可编译的方式解决此问题?

Although documented as being available, apparently it is a documentation bug, since it is not.虽然记录为可用,但显然它是一个文档错误,因为它不是。

However, the man page does point to an alternative interface: sysctl() .但是,手册页确实指向了一个替代接口: sysctl() You can use the sysctlbyname() interface to get the physical memory in bytes.您可以使用sysctlbyname()接口以字节为单位获取物理内存。

#include <iostream>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/sysctl.h>

int main () {
    size_t pagesz = sysconf(_SC_PAGE_SIZE);
    uint64_t mem;
    size_t len = sizeof(mem);
    sysctlbyname("hw.memsize", &mem, &len, NULL, 0);
    std::cout << mem << '\n';
    std::cout << mem/pagesz << '\n';
    std::cout << mem/1024/1024/1024 << '\n';
}

To mimic the functionality for both compilation environments, I would create a wrapper function and modify what the function does based on conditional compilation.为了模拟两种编译环境的功能,我将创建一个包装函数并根据条件编译修改该函数的功能。

#define PHYS_PAGES get_phys_pages()

unsigned get_phys_pages () {
    static unsigned phys_pages;
    if (phys_pages == 0) {
        #if USE_SYSCTL_HW_MEMSIZE
            uint64_t mem;
            size_t len = sizeof(mem);
            sysctlbyname("hw.memsize", &mem, &len, NULL, 0);
            phys_pages = mem/sysconf(_SC_PAGE_SIZE);
        #elif USE_SYSCONF_PHYS_PAGES
            phys_pages = sysconf(_SC_PHYS_PAGES);
        #else
        #   error "no way to get phys pages"
        #endif
    }
    return phys_pages;
}

    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM