I recently wanted to use the header in my application, but I'm not sure if it works on any operating system. (any) because file systems are platform-os dependent. I understand that one of C++'s purposes is cross-platform compilation, but how can it work on any OS when the concept is OS-impl dependent?
2 Answers
It works for the same reason threading works on Linux and Windows where the underlying OS services are vastly different.
The header file (or library code for a non-header-only subsystem) contains enough code to adapt to the platform you're running on.
By way of a very contrived example, file_size()
may call GetFileSize()
under Windows, and stat()
under Linux. I have no idea if that's actually what they do (1) but it would certainly be workable.
And, on a mythical (very simple) OS that can only open/close files and read bytes, it could:
- open the file, fail if cannot be done.
- set a counter to zero.
- until no more bytes in file file:
- read a byte,
- increment counter.
- close the file.
- return counter.
Bottom line, this is all abstracted away so developers have a common set of functions they can call, regardless of what's under the covers.
(1) A very similar method is used in Boost, which sets BOOST_POSIX_API
or BOOST_WINDOWS_API
macros depending on the detected platform:
# if defined(_WIN32) || defined(__CYGWIN__) // Windows default, including MinGW and Cygwin
# define BOOST_WINDOWS_API
# else
# define BOOST_POSIX_API
# endif
Then it makes heavy use of those macros everywhere else in Boost, to decide what code to execute to target the specific platform, such as filesystem/path.cpp
:
#ifdef BOOST_WINDOWS_API
#include "windows_file_codecvt.hpp"
#include "windows_tools.hpp"
#include <windows.h>
#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__HAIKU__)
#include <boost/filesystem/detail/utf8_codecvt_facet.hpp>
#endif
And it's not just for short snippets like that, there are large chunks of function definitions and platform-specific code wrapped up in #ifdef BOOST_WINDOWS_API
conditional compilation sections.

- 854,327
- 234
- 1,573
- 1,953
-
Hence do you think it's just an wrapper on the OS's APIs? – Another HM Feb 28 '23 at 08:22
-
@AnotherHM: it could be. Or it could be more complex (see my "mythical OS" paragraph). But, regardless of *how* it's done, it's done :-) – paxdiablo Feb 28 '23 at 08:24
Each implementation will ship with a different source code that is specific to its environment. The Linux implementation will look completely different from the Windows implementation.
What is common to all implementations though is that they provide the same interface. So an application making use of std::filesystem
doesn't need to worry about how it is implemented internally. They can simply rely that it will provide the functionality specified in the standard.

- 51,484
- 14
- 155
- 166