Cross-Platform C++ code and single header - multiple implementations

前端 未结 5 578
离开以前
离开以前 2021-01-31 11:15

I have heard that a way to write Cross Platform c++ code is to define classes as follows (for example, a Window class):

window.h
window_win32.cpp
window_linux.cp         


        
5条回答
  •  独厮守ぢ
    2021-01-31 11:41

    I would only add a 5) bullet to @Laethnes' answer

    5) Write an empty header that includes, at compile-time, the platform header and hide the platform-specific class under a typedef

    // MyClass.hpp
    
    #if defined(WINDOWS)
    #    include "WINMyClass.hpp"
         typedef WINMyClass MyClass
    #elif defined(OSX)
    #    include "OSXMyClass.hpp"
         typedef OSXMyClass MyClass
    
       ...  // keep going
    
    #endif
    

    Pros:

    • it's only a typedef, very simple
    • good readibility
    • speed

    Cons:

    • it's only a typedef

提交回复
热议问题