It seems like there is an ongoing discussion on whether this is something that should be addressed in upstream CMake and if so how. So unfortunately, there is no “correct” solution provided by CMake and for now every project has to come up with their own approach to solve this.
IMHO a reasonable and well working approach is to use a FindFilesystem
module like this one. Simply save it somewhere in your project (commonly a cmake/
directory) and prepend that path to CMAKE_MODULE_PATH in order to use it. The module performs several check_cxx_source_compiles()
checks (+ 1 hard-coded special case) to figure out which flag is required and then provides and interface target as an abstraction that can be used like this:
find_package(Filesystem REQUIRED)
target_link_libraries(myLib PRIVATE Filesystem::Filesystem)
This approach is analogous to the FindThreads module with its Threads::Threads
target provided by CMake.