CMake test for processor feature

2019-03-01 14:20发布

问题:

I am wondering if it is possible for CMake to run tests like one might run with a configure script. Specifically I want to test if the system I am compiling on has support for the rdtscp instruction.

I am using Linux and if I were using a configure script I could do something like:

cat /proc/cpuinfo | head -n 19 | tail -1 | grep -c rdtscp

which would give me 0 if the rdtscp feature was not present or a 1 if it were. I could then use this to determine whether to #define RDTSCP. I'm wondering if it's possible to do something similar with CMake even if it's not completely portable (I'm only running under Linux I'm not using Visual Studio, etc.).

回答1:

execute_process(COMMAND cat /proc/cpuinfo
    COMMAND head -n 19
    COMMAND tail -1
    COMMAND grep -c rdtscp
    OUTPUT_VARIABLE OUT)


回答2:

Selecting line 19 exactly makes this brittle. On my desktop (Linux 4.20 on i7-6700k), that line is

wp              : yes

Instead use grep's pattern-matching ability to check for the flags\t\t: line.

grep -l '^flags[[:space:]]*:.*rdtscp' /proc/cpuinfo prints the filename and exits with success after the first match. Or prints nothing and exists with failure status if it doesn't find a match.

I don't know CMake, but based on the other answer presumably you'd use

execute_process(COMMAND grep -l '^flags[[:space:]]*:.*rdtscp' /proc/cpuinfo
    OUTPUT_VARIABLE OUT)

The simpler version of this is just grep -l rdtscp /proc/cpuinfo, but requiring a match in the flags : line will prevent any possible false-positive. (To be even more belt-and-suspenders, you could require space or end of line before/after, maybe with PCREgrep for zero-width assertions. In case some future feature flag like XYZrdtscpABC that can be present without RDTSCP support becomes a thing in the future. Or like broken_rdtscp). Or we could just assume that rdtscp is never at the end of the a line and look for ^flags.*:.* rdtscp.

Using -l gets grep to exit after the first match, in case you were using head/tail as an optimization to avoid processing more lines on massively multi-core systems like Xeon Phi? It will still read the whole file if there's no match for rdtscp, but probably any massively-multi-core system will have RDTSCP. And grep is very fast anyway.



标签: linux cmake