【问题标题】:Linux _SC_PHYS_PAGES not working on Mac OS XLinux _SC_PHYS_PAGES 在 Mac OS X 上不工作
【发布时间】:2015-08-11 06:11:01
【问题描述】:

我正在尝试在 Mac OS 上编译一个在 Linux 下不会出现任何问题的项目。我在两个操作系统上都使用 GCC。除了我设法解决的其他问题外,在 OSX 上尝试编译时出现以下错误:

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

unistd.h 包含在发生此错误的文件中。

如何解决这个问题,让代码在 Linux 下仍然可以编译?

【问题讨论】:

    标签: c++ linux macos


    【解决方案1】:

    虽然记录为可用,但显然它是一个文档错误,因为它不是。

    但是,手册页确实指向了另一个接口:sysctl()。您可以使用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';
    }
    

    为了模拟两种编译环境的功能,我将创建一个包装函数并根据条件编译修改该函数的作用。

    #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;
    }
    
        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      相关资源
      最近更新 更多