In autotools one can do the following for example:
which will add the
-lrt flag only when it’s available and needed. (I’m not claiming that my statement is 100% exact, but this one-liner performs a set of tests and as a consequence works across a very wide range of operating systems, compilers and standard libraries and either adds the flag or skips it.)
I would like to use a similar functionality in CMake to figure out whether or not I need the flag
-lstdc++fs to use
std::filesystem (with a C++17-capable compiler). There’s an existing thread in Correct way to link std::filesystem with GCC 8?, but the accepted solution
link_libraries( "$<$<AND:$<CXX_COMPILER_ID:GNU>,$<VERSION_LESS:$<CXX_COMPILER_VERSION>,9.0>>:-lstdc++fs>" ) sounds like a nightmare if I also want to properly support all the compilers and different standard libraries (
stdlibc++). It sounds fine for
gcc, but one needs to do the same for
clang and who-knows-which-other-compilers. Another solution uses 60 lines of code to achieve roughly the equivalent of what autotools do with a single line.
What I would really like to achieve is the following:
- try to compile with the
- try to compile without the flag
(I don’t care in which order) and provide feedback about the option that works correctly for
std::filesystem, without having to provide tons of hardcoded knowledge about various compiler and operating system versions (that require, don’t require or refuse to work with that flag).
In this particular case I don’t want to care too much about really old compilers, but supporting gcc 8 (for Debian and Ubuntu) is still somewhat unavoidable, and I definitely need support for clang on various operating systems.