![]() |
|
|
#1 |
|
Архивный участник
Join Date: Nov 2004
Posts: 1,405
|
Porting C++ and C code to other operating systems
by Ramsey Porting C/C++ code is easier than you think. To go about doing so, look over your code an CLEAN IT UP. Then, remove and replace any OS specific calls for example the system() call in windows to another alternative. Example: CODE Win32 Pause: system("pause"); --------------------------- Universal Pause (Linux, Win32, BSD etc.) printf("Press any key to continue\n"); //Put whatever message you want for the pause, not required cin.get(); After doing so, you will find porting much easier. Before you can actually port, you must understand "PreCompiler Directives" and the #ifdef. This allows you to define what portion of code you want a certain OS to execute (decided during compile time). The #ifdef family works just like if statements for example, #elif is Else If. #ifdef example, Linux, Windows Heres a pretty straight forward example of how the ifdef works. CODE #include <iostream> using namespace std; int main() { cout<<"Your Operating System is: "; #ifdef WIN32 //On Compile, if the OS is Windows Then: cout<<"Windows!\n"; cin.get(); #elif __linux //Else If the OS is Linux then: cout<<"Linux!\n"; cin.get(); #else //If it isnt Windows or Linux, set as unknown: cout<<"Unknown!\n"; cin.get() #endif //EndIf required. return 0; } Wow! I actually understand how this works! So how does it come into Server Emulation? If you have done Sockets in Linux and Windows, you already know there are some slight differences. Here are some examples: Winsock: CODE #ifdef WIN32 WSADATA wsaData; //use of WS2_32.DLL WSAStartup(0x202,&wsaData); //Loads the library #endif In linux, you dont need to do this. Also when closing a socket: CODE #ifdef WIN32 cout<<"Closing socket..\n"; closesocket(serversock); //Closes Socket cout<<"WSACleanup...\n"; WSACleanup(); //The Clean up, not required but makes things much faster. #elif __linux close(serversock); #endif You must know that you have to recompile the source on each individual platform. You cant just compile it on Windows and expect it to run on Linux. You must recompile, the compiler runs through the code and adds a section of code where the OS its running on is called, then ignores the other OS's. Hope this gave a little insight on how to port code, I did this in a bit of a hurry so please excuse my spelling and grammer. |
|
|
|
|