endian_check.cpp

Go to the documentation of this file.
00001 /* $Id: endian_check.cpp 17248 2009-08-21 20:21:05Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00019 #include <stdio.h>
00020 #include <string.h>
00021 
00023 enum Endian {
00024   ENDIAN_LITTLE, 
00025   ENDIAN_BIG     
00026 };
00027 
00032 static inline void printf_endian(Endian endian)
00033 {
00034   printf("#define TTD_ENDIAN %s\n", endian == ENDIAN_LITTLE ? "TTD_LITTLE_ENDIAN" : "TTD_BIG_ENDIAN");
00035 }
00036 
00043 int main (int argc, char *argv[])
00044 {
00045   unsigned char endian_test[2] = { 1, 0 };
00046   int force_BE = 0, force_LE = 0, force_PREPROCESSOR = 0;
00047 
00048   if (argc > 1 && strcmp(argv[1], "BE") == 0) force_BE = 1;
00049   if (argc > 1 && strcmp(argv[1], "LE") == 0) force_LE = 1;
00050   if (argc > 1 && strcmp(argv[1], "PREPROCESSOR") == 0) force_PREPROCESSOR = 1;
00051 
00052   printf("#ifndef ENDIAN_H\n#define ENDIAN_H\n");
00053 
00054   if (force_LE == 1) {
00055     printf_endian(ENDIAN_LITTLE);
00056   } else if (force_BE == 1) {
00057     printf_endian(ENDIAN_BIG);
00058   } else if (force_PREPROCESSOR == 1) {
00059     /* Support for universal binaries on OSX
00060      * Universal binaries supports both PPC and x86
00061      * If a compiler for OSX gets this setting, it will always pick the correct endian and no test is needed
00062      */
00063     printf("#ifdef __BIG_ENDIAN__\n");
00064     printf_endian(ENDIAN_BIG);
00065     printf("#else\n");
00066     printf_endian(ENDIAN_LITTLE);
00067     printf("#endif\n");
00068   } else if (*(short*)endian_test == 1 ) {
00069     printf_endian(ENDIAN_LITTLE);
00070   } else {
00071     printf_endian(ENDIAN_BIG);
00072   }
00073   printf("#endif\n");
00074 
00075   return 0;
00076 }

Generated on Wed Feb 17 23:06:46 2010 for OpenTTD by  doxygen 1.6.1