Compile time architecture detection in cmake
So I have a library I'm working on that has, or will have, optimised assembly per architecture of the cpu. We're talking about optimising for nehalem, or core2, or k8 or whatever.
Anyway, I've been experimenting with build systems recently and have managed to set up the following with CMake:
add_executable(arch/cpuid_x86 arch/cpuid_x86.c)
execute_process(COMMAND ${PROJECT_BINARY_DIR}/arch/cpuid_x86
OUTPUT_VARIABLE PROJECT_CPUID OUTPUT_STRIP_TRAILING_WHITESPACE)
This does what you think it does. cpuid_x86.c
is a little c program with some inline assembly to call the cpuid
instruction. It deduces the archi开发者_运维知识库tecture string from the integer result of said instruction, writing that to stdout.
Now, the above works, I can then use that output directly in a header file, or I assume to construct filenames, which is the idea.
However, I'm new to cmake, and I just feel like this is a bit of a hack. Perhaps it isn't, so my question is am I using cmake the right way here? Am I stumbling onto unforeseen problems anywhere?
You are probably better off using try_run
, which will compile and run the code for you. Be aware that you're introducing issues when cross-compiling, unless you're happy to fall back to generic x86 code (or force the person building your code to manually set cache variables). This will let you store the name of the subarchitecture in a CMake variable, which you can then substitute into a header with something like configure_file
.
精彩评论