Reputation: 33
I want to make a program work and compile in both WIN\Linux .
I want to have some information about the OS which my program is ran on.
moreover I want to have a variable to decide about the code i want to be performed.
I thought about a pre-processed code to have an input to my controlling variable which I described.
So, I must have something like:
# //a preprocess code to detect the os
# define controllingVar // ?
I use C++;
Upvotes: 1
Views: 251
Reputation: 28762
You can deduce what platform your code is being compiled for by using (compiler specific) pre-processor macros, like WIN32 and the like. There is no easy way to deduce what platform your program is running on (other than it is most likely running on a platform it was compiled for) -- you will need to perform platform/OS specific calls for that.
You could do something like this:
#ifdef WIN32 // compiler specific, WIN32 is defined in Visual Studio
// Windows specific code
// include Windows specific headers
int controllingVar = 0; // 0 - Windows
#else
// For everything else
// Here: assume Unix/Linux
// include Linux specific headers
int controllingVar = 1; // 1 - non-Windows
#endif
After this you can refer to controllingVar
in your code. controllingVar
will have the value 0 if the program was compiled for Windows, 1 otherwise (and you can go with the assumption of Linux).
The #ifdef
part enables conditional compilation -- the code within the Windows specific block is compiled only when compiled for Windows, the other in any other case.
Note that this essentially requires a duplication of coding, maintenance and testing efforts, so try to put only the most essential code in the conditional blocks and anything that is not platform specific outside it.
Upvotes: 1
Reputation: 21900
You could check if the WIN32 macro has been defined:
#ifdef WIN32
// do windows stuff
#else
// do GNU/Linux stuff
#endif
Note that on some compilers, you might also have to check for _WIN32
, as stated in wikipedia.
As an example:
#ifdef WIN32
void foo() {
std::cout << "I'm on Windows!\n";
}
#else
void foo() {
std::cout << "I'm on GNU/Linux!\n";
}
#endif
Edit: since you're asking about different main
s for each OS, here's an example:
int main() {
#ifdef WIN32
// do whatever you want when executing in a Windows OS
#else
// do the same for GNU/Linux OS.
#endif
}
You could also have different main
s:
#ifdef WIN32
int main() {
//windows main
}
#else
int main() {
//GNU/Linux main
}
#endif
Upvotes: 3