1

I am writing a C program and my operating system is MacOS. I am wondering how to add a macro in order to compile my C program under different operating system, mainly Windows and Linux?

Thanks a lot for providing me an idea on this question.

Boooooooooms
  • 306
  • 4
  • 21
  • Whats the macro supposed to do? – tkausl May 14 '18 at 15:13
  • 1
    It very much depends on what system-dependent things your program is relying upon. – Christian Gibbons May 14 '18 at 15:18
  • 1
    Why not to create different blocks in your makefile according to your target? passing the target as additional information, in this topic it is well explained: https://stackoverflow.com/questions/2826029/passing-additional-variables-from-command-line-to-make and different targets: https://stackoverflow.com/questions/13919505/how-to-build-multiple-targets-from-one-makefile – Jose May 14 '18 at 15:18
  • 3
    I wouldn't use macros but an OS abstraction layer. Then it's easy to switch between MacOS, WindowsOs and LinuxOS when compiling. – Support Ukraine May 14 '18 at 15:30
  • 1
    As @4386427 says - you should **design** to be portable. Separate out the portable and non-portable code. Put the OS dependant code into a separate set of functions and compile into a DLL/.so file. It takes much more work initially but saves a huge amount of effort in the long run. – cdarke May 14 '18 at 16:03

1 Answers1

1

You can do it like below:-

#if defined(_WIN32)
    #define OS_NAME "windows"
    /* add your windows specific codes here */
#elif defined(__linux__)
    #define OS_NAME "linux" 
    /* add your Linux specific codes here */
#elif defined(__APPLE__) && defined(__MACH__)
   #define OS_NAME "MacOS"
   /* add your Mac specific codes here */    
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17