How to compile a C program that includes the Winsock library on Mac OS X

I am developing a portable client-server application in C. I would like to be able to compile it on Mac OS X as well as Linux and Windows. I am currently working with Mac OS X. I am trying to achieve this result using preprocessor directives like this:

#include <stdio.h>
#include <stdlib.h>

#if defined WIN32
#include <winsock.h>
#else
#define closesocket close
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif

int main(void) {

#if defined WIN32

    WSADATA wsaData;
    WORD wVersionRequested;
    wVersionRequested = MAKEWORD(2, 2);
    int iResult = WSAStartup(wVersionRequested, &wsaData);
    if (iResult != 0){
        printf("Error at WSAStartup()\n");
        printf("A usable WinSock DLL cannot be found");
        return 0;
    }

#endif

    int Mysocket;

    //***MyCode***

    closesocket(Mysocket);

#if defined WIN32
    WSACleanup();
#endif

    return 0;

}

      

When it comes to compiling this code on Mac OS X, the compiler cannot find "winsock.h". Of course, the file and the libraries it points to are not present in Mac OS X. Anyway: shouldn't I use the preprocessing directives I used to avoid this problem when I work with Mac OS X and Linux? And if they don't, is there a way to design such a program in such a way that, once completed, it can be compiled on all the platforms I mentioned?

+3


source to share





All Articles