I am currently using the popen
function in code that is compiled by two compilers: MS Visual Studio and gcc (on linux). I might want to add gcc (on MinGW) later.
The function is called popen
for gcc, but _popen
for MSVS, so i added the following to my source code:
#ifdef _MSC_VER
#define popen _popen
#define pclose _pclose
#endif
This works, but i would like to understand whether there exists a standard solution for such problems (i recall a similar case with stricmp
/strcasecmp
). Specifically, i would like to understand the following:
_MSC_VER
the right flag to depend on? I chose it because i have the impression that linux environment is "more standard".#define
's in some header file, is it important whether i #include
it before or after stdio.h
(for the case of popen
)?_popen
is defined as a macro itself, is there a chance my #define
will fail? Should i use a "new" token like my_popen
instead, for that reason or another?The way you are doing it is fine (with the #ifdef
etc) but the macro that you test isn't. popen
is something that depends on your operating system and not your compiler.
I'd go for something like
#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 2)
/* system has popen as expected */
#elif defined(YOUR_MACRO_TO DETECT_YOUR_OS)
# define popen _popen
# define pclose _pclose
#elif defined(YOUR_MACRO_TO DETECT_ANOTHER_ONE)
# define popen _pOpenOrSo
# define pclose _pclos
#else
# error "no popen, we don't know what to do"
#endif
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