How can I make my source code portable

Aug 3, 2009 at 1:38pm
Say I have for unix I have a header file that does some function that is implemented differently in windows( e.g. sleep), how can I make it such that my code can be compiled on both windows and linux?

I know in the past for windows it is done this way

#ifdef WIN32
#include "header.h"
#endif

Does it still work today?
What is the linux/unix equivalent it?
Aug 3, 2009 at 9:28pm
I would say the WIN32 macro still applies. You don't have to use it to include entire files, however.

Example of a single header file that works on multiple platforms:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Sample.h

#pragma once

#ifndef __Sample_h__
#define __Sample_h__

//Windows headers
#ifdef WIN32

extern "C" __stdcall SomeFunction(DWORD someArg);

#elif !defined SOMEMACROTHATDEFINESMACINTOSH

....

#endif //WIN32

#endif 


I only program for Windows, but I have seen this construct in some of the header files. You might want to check this method out a bit more in depth.
Aug 3, 2009 at 9:52pm
The equivalent of WIN32 in UNIX is unix.
1
2
3
#ifdef unix
#include <unistd.h>
#endif 
Aug 4, 2009 at 1:39pm
Does anyone know the macro for mac?
Aug 4, 2009 at 3:04pm
MacOS X and above is a kind of UNIX.
Aug 4, 2009 at 9:03pm
For compiler macros, see Pre-defined C/C++ Compiler Macros
http://predef.sourceforge.net/

Typically, platform differences are handled by the build process.
Google around autoconf and automake for more.

So, I may have a file named

myproject\Win32\console.cpp

and another file named

myproject\POSIX\console.cpp

for console functionality. Depending on the system I am compiling, the build process will compile and link the appropriate source file.

Hope this helps.
Topic archived. No new replies allowed.