20

I noticed that in MacOS X (Lion), the macro __unix__ is not defined. Since MacOS has its roots in BSD UNIX, shouldn't that be the case?

Is it possible to let the compiler/preprocessor know that I want it to be considered a UNIX system?

Pietro
  • 12,086
  • 26
  • 100
  • 193
  • You might have more luck with the POSIX macros instead http://sourceforge.net/apps/mediawiki/predef/index.php?title=Standards#Unix_Standards – Flexo Aug 15 '11 at 09:16
  • See also: [Common macro to identify a UNIX derived system? (Linux, OSX, BSD, …)](https://stackoverflow.com/questions/7917520) – hippietrail Apr 06 '21 at 04:32

2 Answers2

19

I think this site gives the most comprehensive answer.

In short, to include Apple platforms and common Unix platforms, you'll need:

#if defined(__unix__) || defined(__unix) || \
        (defined(__APPLE__) && defined(__MACH__))
...
#endif
metamorphosis
  • 1,972
  • 16
  • 25
Yongwei Wu
  • 5,292
  • 37
  • 49
18

The predefined macros site suggests using:

#if defined(unix) || defined(__unix__) || defined(__unix)
# define PREDEF_PLATFORM_UNIX
#endif

To distinguish UNIX systems. They also have warning notes about a number of compilers that don't set any of these. Depending on why you care about what the platform is you might be better off looking at configure time (in configure.ac or whatever build system you're using).

Flexo
  • 87,323
  • 22
  • 191
  • 272
  • 5
    ./configure is not universal. In fact, it is mainly used in Unix and Unix-like platforms. Using it to detect "Unix" platforms does not sound good to me. – Yongwei Wu Apr 19 '13 at 14:56
  • It is universal if you write you own. You can write your own, or equivalent component for almost any build system that matters. In CMake you write a test in CMakeLists.txt, in autotools you write test in configure.ac, in ant you can do similar inside your XML. Scons has a similar concept too I believe, as does Python's distutils. – Flexo Aug 01 '17 at 07:08
  • 1
    On Windows, you do not have Bash installed by default, and how can you ./configure? My other point was that ./configure is basically Unixy in the beginning: using it to detect Unix is like chasing the tail. – Yongwei Wu Aug 01 '17 at 12:35
  • There are plenty of other tools that are cross platform that do have a configure stage even if they're not called ./configure. CMake being the obvious one, for this use case was why I qualified that recommendation with "or whatever build system you're using" – Flexo Aug 01 '17 at 17:32
  • 3
    According to the [site](http://web.archive.org/web/20160306052035/http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system) linked in the answer by Yongwei Wu, Apple compilers don't define either `unix`, `__unix` or `__unix__`, so I really don't understand how this was upvoted and set as correct answer by original poster. – ceztko Feb 26 '20 at 14:08