Is there a code style or design for cross-platform without #ifdef preprocessing (C++17)?

Viewed 27

I am currently editing Windows Cpp codes for Linux.

But, the way I know

example 1

template <typename T>
static off_t SetFilePointerU(T handle, unsigned int fileOffset, const int flag)
{
#ifdef _WIN32

    return ::SetFilePointer(static_cast<void*>(handle), fileOffset, NULL, flag);

#elif __linux__
    
    return lseek(handle, fileOffset, flag);

#endif
}
template <typename T>
static unsigned long ReadFileU(T handle, void* readBuffer, const int readSize = READ_BUFFER_SIZE)
{
#ifdef _WIN32

    DWORD outReadSize;

    if (!::ReadFile(static_cast<void*>(handle), readBuffer, readSize, &outReadSize, NULL))
    {
    
    }

    return outReadSize;

#elif __linux__

    return read(handle, readBuffer, readSize);

#endif
}

example2

#ifdef __linux__
            std::wstring u16FilePath{ updateInfo.strFilePath.begin(), updateInfo.strFilePath.end() };
            std::wstring u16FileName{ updateInfo.strFileName.begin(), updateInfo.strFileName.end() };
            auto pathList = deSerializer.GetRealPaths(u16FilePath);
#elif _WIN32
            auto pathList = deSerializer.GetRealPaths(updateInfo.strFilePath);
#endif

            for (auto& path : pathList)
            {
#ifdef __linux__
                std::u16string u16toWstringPath{ path.begin(),path.end() };
                updateInfo.strFilePath = u16toWstringPath;
#elif _WIN32
                updateInfo.strFilePath = path;
#endif
                if (updateInfo.updateType == 0)
                {
#ifdef __linux__
                    path.append(u16FileName);
#elif _WIN32
                    path.append(updateInfo.strFileName);
#endif
                    std::transform(path.begin(), path.end(), path.begin(), tolower);
                    updateDatInfos.emplace(path, updateInfo);
                }
                else
                { 
#ifdef _WIN32
                    updateDatInfofilePath = updateInfo.strFilePath;
                    updateDatInfofilePath += L"\\";
                    updateDatInfofilePath += updateInfo.strFileName;
                    std::filesystem::remove(updateDatInfofilePath);
#elif __linux__
                    std::u16string u16UpdateDatInfofilePath{ updateInfo.strFilePath.begin(), updateInfo.strFilePath.end() };
                    u16UpdateDatInfofilePath += u"/";
                    u16UpdateDatInfofilePath += updateInfo.strFileName;
                    std::filesystem::remove(u16UpdateDatInfofilePath);
#endif

This is the same way as above.

I think that there is a lot of preprocessing in the code, and the readability may decrease in the future. Are there other methods for cross-platform development?

Q)I am using ifdef in several places in my code. But I don't want to use #ifdef in multiple places in multiple files.

Is there any other good way?

0 Answers
Related