Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why include direct.h or sys/stat.h conditionally based on _WIN32 or __linux__?

Tags:

c

ifdefine

What will the following code do? Why is it used?

  #ifdef _WIN32
  #include <direct.h>
  #elif defined __linux__
  #include <sys/stat.h>
  #endif
like image 981
Bosnia Avatar asked Aug 13 '14 07:08

Bosnia


2 Answers

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.

like image 151
Mohit Jain Avatar answered Sep 21 '22 13:09

Mohit Jain


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/Linux

It works just like a classical if/else statement:

if(platform == windows)
{
    take_windows_lib();
}
else if (platform == linux)
{
    take_linux_lib();
}
like image 32
n0p Avatar answered Sep 23 '22 13:09

n0p