Is there a way to determine how many physical cores a target machine has at compile time in C/C++ in Linux under GCC?
I am aware of other methods like std::thread::hardware_concurrency()
in C++11 or sysconf(_SC_NPROCESSORS_ONLN)
but I am curious to know if there is actually a way to obtain this information at compile time.
You can query information during the build processes and pass it into the program as a pre-processor definition.
Example
g++ main.cpp -D PROC_COUNT=$(grep -c ^processor /proc/cpuinfo)
where main.cpp
is
#include <iostream>
int main() {
std::cout << PROC_COUNT << std::endl;
return 0;
}
Edit
As pointed out in the comments. If the target machine differs from the build machine then you'll need to replace the method grep -c ^processor /proc/cpuinfo
with something that queries the number of processors on the target machine. The details would depend on what form of access you have to the target machine during build.