#How do I write cross-platform code?

7 messages · Page 1 of 1 (latest)

grim palm
#

how do I write cross-platform code? with preprocessor directives, the code will be completely unreadable. In Google, I saw that they offer to write their own code in their own folder for each system, but this is also not the best option because I will have to completely rewrite my entire project 3 times. I thought that I could do such a thing: let's say I have a function that looks something like this:

void Application::Init() {
    CConsole::PrintLn("Initializing CBaseApplication...");
#ifdef _WIN32
    SetConsoleCP(CP_UTF8);
    SetConsoleOutputCP(CP_UTF8);
    CConsole::PrintLn("Console code page: %d", CP_UTF8);

    wchar_t buffer[MAX_PATH];

    if (GetModuleFileName(nullptr, buffer, MAX_PATH) == MAX_PATH) {
        wchar_t* errorMsg;
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorMsg, 0, nullptr);
        throw std::runtime_error(Utf16ToUtf8(errorMsg).c_str());
    }

    rootDir = buffer;
    rootDir.remove_filename();
    CConsole::PrintLn("rootDir == %s", rootDir.string().c_str());
#else
    rootDir = std::filesystem::canonical("/proc/self/exe");
    CConsole::PrintLn("rootDir == %s", rootDir.string().c_str());
#endif
    CConsole::PrintLn("Initializing finished.\n");
}

And I could create two files: one posixapp.cpp , the second winapp.cpp and they write the implantation of this function

But I'm afraid that this file will grow to an incredibly large size. What should I do anyway?

noble lakeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

soft acorn
#

Use abstractions

#

You shouldn't need that much platform-dependent code so don't worry about rewriting everything

#

With abstractions you ideally can reuse most of the code

scarlet bronze
grim palm
#

thx