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"
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.
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 #ifdef
s will always give the correct result (unless you mess with the compiler)
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.
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
.
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