Reputation: 526
I have the following code that I want to work also on Linux with GCC 4.8
This is working with VS 2013
if ( _access( trigger->c_str(), 0 ) != -1 )
{
...
}
I know that on Linux I can use function: access from "unistd.h"
Is there a way to avoid having something like the following ( a more elegant solution ) ?
#ifdef __linux__
#include <unistd.h>
#endif
#ifdef __linux__
if ( access( trigger->c_str(), 0 ) != -1 )
{
...
}
#else
if ( _access( trigger->c_str(), 0 ) != -1 )
{
...
}
#endif
Upvotes: 5
Views: 6228
Reputation: 238351
A solution that has no duplication, nor relies on a macro definition (besides the predefined one for platform detection) but has slightly more boilerplate than Aracthor's solution:
#ifdef _WIN32
inline int access(const char *pathname, int mode) {
return _access(pathname, mode);
}
#else
#include <unistd.h>
#endif
I prefer to detect windows, and use posix as fall back, because windows tends to be the exception more often than linux.
Another clean solution would be to define _CRT_NONSTDC_NO_WARNINGS
and keep using the POSIX standard access
in windows, without warnings about deprecation. As a bonus, this also disables warnings for using the standard strcpy
instead of strcpy_s
and similar. The latter is also standard (in C11), but optional and hardly any other C library implements them (and also, not all of the _s
family functions in msvc comply to C11).
Upvotes: 8
Reputation: 5907
There is another way, header-only solution.
#ifdef __linux__
#include <unistd.h>
#else
#define access _access
#endif
if ( access( trigger->c_str(), 0 ) != -1 )
{
...
}
It would include the right file on Linux systems and replace access
with _access
on other systems.
Upvotes: 3