lundi 16 mars 2020

Can someone please help me how to move the code that was written using #ifdef to support multiple platforms into the library function?

We have a C++ project that is supporting multiple platforms (windows, linux, and mac).

To support multiple platforms, we have the below code snippet to close an existing socket for all the platforms.

#ifdef _WIN32
       closesocket(m_nSocketHandle);
#elif __APPLE__
      close(m_nSocketHandle);
#elif __linux__
        shutdown(m_nSocketHandle,SHUT_RDWR);
#endif

Similarly we are using other APIs for eg mkdir for different OS:

#ifdef _WIN32
        if (0 == _mkdir(m_hStrDirectoryPath.c_str()))
#else
    #ifdef __linux
            char mkcmd[500];
            sprintf(mkcmd, "mkdir -p %s", SDK_PATH);
            system(mkcmd);
             if (0 == mkdir(m_hStrDirectoryPath.c_str(), 0777))

    #else
            if (0 == mkdir(m_hStrDirectoryPath.c_str(), 0777))
    #endif
#endif

Instead of writing the code like this for all patforms or operating systems can we write a library (for eg., commonlib) by using the above code in the below function:

for eg.,

close_socket()
{
#ifdef _WIN32
      closesocket(m_nSocketHandle);
#elif __APPLE__
      close(m_nSocketHandle);
#elif __linux__
        shutdown(m_nSocketHandle,SHUT_RDWR);
#endif
} 

And call this function from the main application, is this possible? Can someone please provide your inputs/suggestions and sample to understand?

Aucun commentaire:

Enregistrer un commentaire