What will the following code do? Why is it used?
#ifdef _WIN32
#include <direct.h>
#elif defined __linux__
#include <sys/stat.h>
#endif
There is no portable way in C to manipulate file system directories. You need some library that provides wrapper interfaces to manipulate directories. (Using system call, OS interrupts routines etc)
direct.h
is a header file for the C programming language for windows. It contains declaration of functions and required macros, struct etc used to manipulate file system directories. In Linux like system, you can use sys/stat.h
for the same.
Now if your code may be compiled for either of the OS, you can keep the common (portable) code without any guards and keep windows-specific or linux-specific code in conditional compilation block.
If you don't include those files conditionally, you may get direct.h not found
or similar error in Linux and any similar error for windows.
__linux__
is pre-defined by the compiler targeting the code for Linux.
This msdn document says:
_WIN32: Defined for applications for Win32 and Win64. Always defined.
This is a conditional statement but for compilation time. When the program is compiled, it looks for the platform it is running on and includes the proper header for your OS (these libraries are implemented for a specific OS):
direct.h
for windows sys/stat.h
for GNU/LinuxIt works just like a classical if/else
statement:
if(platform == windows)
{
take_windows_lib();
}
else if (platform == linux)
{
take_linux_lib();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With