canfiese
canfiese

Reputation: 61

C++: <sys/sysctl.h> fails to declare functions CTL_HW and HW_NCPU

Aloha all!

I'm working with the following script (which I did not write). This is one of many files I've been working on modifying to initiate a build/make on Linux.

Everything I've found online suggests that sys/sysctl.h should properly declare these functions:

CTL_HW and HW_NCPU

However, running the following (called "machineInfo.cpp"):

#include "machineInfo.h"

#include <sys/sysctl.h>
#include <linux/sysctl.h>
#include <cstdio>

#define ARRAY_SIZE(a) (sizeof (a) / sizeof ((a)[0]))

int StMachineInfo::numProcs(void) {

    int numCPU = 0;
    int nprocs;
    size_t len = sizeof(nprocs); 
    static int mib[2] = { CTL_HW, HW_NCPU };

    /* get the number of CPUs from the system */
    sysctl(mib, 2, &numCPU, &len, NULL, 0);

    if( numCPU < 1 ) 
        {
        mib[1] = HW_NCPU;

        if (sysctl (mib, ARRAY_SIZE(mib), &nprocs, &len, NULL, 0) == 0 && len == sizeof (nprocs) && 0 < nprocs)
            numCPU = nprocs;

        if( numCPU < 1 )
            numCPU = 1;
        }
    return numCPU;

}

...results in the following error output:

g++  -c machineInfo.cpp
machineInfo.cpp: In function ‘int StMachineInfo::numProcs()’:
machineInfo.cpp:14:24: error: ‘CTL_HW’ was not declared in this scope
  static int mib[2] = { CTL_HW, HW_NCPU };
                        ^
machineInfo.cpp:14:32: error: ‘HW_NCPU’ was not declared in this scope
  static int mib[2] = { CTL_HW, HW_NCPU };
                                ^
Makefile:33: recipe for target 'machineinfo.o' failed
make: *** [machineinfo.o] Error 1

Is there something wrong with the code itself? Or do I need to #include another header? I've experimented with this and Googled for a couple of hours, to no avail.

Many thanks,

Sean

Upvotes: 0

Views: 1745

Answers (1)

Jason R. Coombs
Jason R. Coombs

Reputation: 42659

I believe the problem here is that sysctl does not have a glibc wrapper on Linux. By my best understanding, those constants are only available on BSD.

I'd be happy to be proven wrong, as I'm trying to understand if this uname -p behavior could ever work on Linux.

Upvotes: 2

Related Questions