View Full Version : Portable, word-size independent C code
Paul C. Anagnostopoulos
25th October 2007, 04:08 PM
So this is kind of a broad question, but what the heck. Let's say I want to write a large C/C++ application that is as portable as possible, both in terms of machine and OS, and also can be compiled as a 32-bit or 64-bit application. What is the right way to structure such a program?
Does Posix solve the portability problem?
What fancy tricks do I perform in some header file to define all the basic datatypes in a way that is portable and can be switched between 32-bit and 64-bit?
I've done this before, but it's been awhile and I figure y'all have good ideas about it.
~~ Paul
Stimpson J. Cat
26th October 2007, 05:26 AM
I would say the first step is to make use of the C99 fixed size integer types whenever a specific size is needed (for example, if you are going to be accessing data stored in binary files which need to be portable between platforms), and make use of the provided typedefs like size_t, ptrdiff_t, and off_t when dealing with integers whose size may vary with platform.
I've been doing this in my own code for some time, since most of my stuff needs to be able to run on both Windows and Linux, and needs to be both 64bit and 32bit compatible. The biggest challenge is in file-io on 32bit systems. The standards do not make any allowances for normal pointers and file pointers being different sizes, so the workarounds tend to be very platform specific. What I have done is provide my own typedef for integers that represent differences between file locations (which is what off_t is supposed to do), and then consistently use that. The only remaining problem is using the right functions for seeking. The C standard does not provide adequate file seeking functions (its functions take ints or longs as its arguments, which is not portable), so you have to use the posix functions (if available).
On posix systems this is easy, because there you can usually just define a precompiler option to make sure that off_t is 64bit, and that the right file seeking functions are used. But when you don't have posix support, it becomes more work. With MinGW (gcc for Windows), the functions have slightly different names, so I have to essentially use wrapper functions that provide a uniform interface for all platforms.
Dr. Stupid
Paul C. Anagnostopoulos
26th October 2007, 09:13 AM
Thanks, Stimpy.
~~ Paul
© 2001-2009, James Randi Educational Foundation. All Rights Reserved.
vBulletin® v3.7.7, Copyright ©2000-2012, Jelsoft Enterprises Ltd.