Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know what OS I'm working in?

Tags:

c++

c

I need a function that can clear the screen in both Linux and Windows. To do this, I want to know if there are some instructions that can tell me what operating system I'm working with. I have searched for solution and I found the following code:

void clear_screen()
{
   #ifdef WINDOWS

    std::system ( "CLS" );

    #else

    // Assume POSIX

    std::system("clear");

    #endif
}

There are two problems with this function:

  • I don't understand it.

    -> for #ifdef WINDOWS, where is WINDOWS defined?

  • This code works in Linux but it doesn't work in Windows.

Note :

  • I'm using Windows XP.

  • I don't want any non-standard functionality ... such "curses"

like image 366
Az.Youness Avatar asked Jun 18 '13 12:06

Az.Youness


4 Answers

Macros such as _WIN32, __gnu_linux__, __linux__ are defined by the compiler in question. You can find a comprehensive list of pre-defined compiler macros here.

_WIN32 is defined for both 32-bit and 64-bit environments of Windows.

like image 155
devnull Avatar answered Sep 23 '22 20:09

devnull


You're looking for

// Windows, all variants (including 64-bit and ARM)
#ifdef _WIN32

or

#ifdef __unix__

These are defined by your compiler, and are not stored in a header file. Because of that, you don't need to #include a file first, and these #ifdefs will always give the correct result (unless you mess with the compiler)

like image 38
Tom van der Woerdt Avatar answered Sep 25 '22 20:09

Tom van der Woerdt


WINDOWS is defined by your compiler, so this defines can be compiler-dependant. It's usefull in order to compile specific code depending on your OS.

like image 34
nouney Avatar answered Sep 24 '22 20:09

nouney


There are various compiler-dependant macros. Unfortunately, they are not particularly useful, because they are not standardized and a C compiler for a particular OS does not necessarily #define them. I also suspect that they actually violate the C standard C11 7.1.3.

The 100% portable solution, which will compile on all C compilers, is to create such a constant yourself. Since C is a compiled language, you will have to compile your code differently for each OS anyhow. Simply add a file called os.c where you put a relevant #define or constant, then link this to your program. The only thing you need to change when compiling for a different OS is the make file path to your OS-specific os.c.

like image 23
Lundin Avatar answered Sep 26 '22 20:09

Lundin