Writing cross-platform C++ Code (Windows, Linux and Mac OSX)

前端 未结 5 1213
予麋鹿
予麋鹿 2021-01-29 19:48

This is my first-attempt at writing anything even slightly complicated in C++, I\'m attempting to build a shared library that I can interface with from Objective-C, and .NET app

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 19:56

    I'll address this specific function:

    bool probe() {
    #ifdef TARGET_OS_MAC
      return probe_macosx();
    #elif defined __linux__
      return probe_linux();
    #elif defined _WIN32 || defined _WIN64
      return probe_win();
    #else
    #error "unknown platform"
    #endif
    }
    

    Writing it this way, as a chain of if-elif-else, eliminates the error because it's impossible to compile without either a valid return statement or hitting the #error.

    (I believe WIN32 is defined for both 32- and 64-bit Windows, but I couldn't tell you definitively without looking it up. That would simplify the code.)


    Unfortunately, you can't use #ifdef _WIN32 || _WIN64: see http://codepad.org/3PArXCxo for a sample error message. You can use the special preprocessing-only defined operator, as I did above.


    Regarding splitting up platforms according to functions or entire files (as suggested), you may or may not want to do that. It's going to depend on details of your code, such as how much is shared between platforms and what you (or your team) find best to keep functionality in sync, among other issues.

    Furthermore, you should handle platform selection in your build system, but this doesn't mean you can't use the preprocessor: use macros conditionally defined (by the makefile or build system) for each platform. In fact, this is the often the most practical solution with templates and inline functions, which makes it more flexible than trying to eliminate the preprocessor. It combines well with the whole-file approach, so you still use that where appropriate.

    You might want to have a single config header which translates all the various compiler- and platform-specific macros into well-known and understood macros that you control. Or you could add -DBEAKS_PLAT_LINUX to your compiler command line—through your build system—to define that macro (remember to use a prefix for macro names).

提交回复
热议问题