Home  >  Q&A  >  body text

C++ 如何兼容Linux和window?

有时在C++ 中调用有关操作系统的函数时,需要不同的头文件,(例如Sleep()函数window下在头文件windows.h,Linux下是system.h并且函数名的S改为小写),这样容易产生两份不同的代码,有没有办法再同一份代码下兼容两个平台?

迷茫迷茫2744 days ago975

reply all(7)I'll reply

  • 高洛峰

    高洛峰2017-04-17 14:35:29

    You need to encapsulate the differences between platforms yourself

    void Sleep(const unsigned int milliseconds)
    {
    #ifdef _WIN32
       ::Sleep(milliseconds);
    #else
       usleep(milliseconds * 1000);
    #endif
    }

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:35:29

    This problem is basically encountered by all languages. Even if JAVA is compiled once and can be run everywhere, it is because the virtual machine helps to cover up the implementation details of various platforms, leaving only unity for the upper layer. interface.
    Although the C++ standard library does not provide a corresponding solution, macro facilities such as #ifdef can help us span different platforms. If the workload is heavy, you can simply use a third-party cross-platform library for C++. , the workload is small, it is recommended to encapsulate it a little yourself.
    Third parties can use libraries such as boost and QT. For simple sleep, c++11标准模板库 provides std::this_thread::sleep_for

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:35:29

    You can use boost library: http://www.boost.org/ Each API has been packaged across platforms.

    reply
    0
  • PHPz

    PHPz2017-04-17 14:35:29

    Any issues with the code can be solved by adding layers.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:35:29

    Use macros.
    ifdef determines whether it is win32, if not, define Sleep(xxxxx) sleep(xxxx/1000)

    Or directly use the libc function

    There is another way, compile with cygwin, but this will have dependent dll

    reply
    0
  • 黄舟

    黄舟2017-04-17 14:35:29

    Encapsulation. Encapsulate all functions that may cause platform problems yourself, and then use conditional compilation to distinguish them. The sleep you mentioned is just a simple problem, and many details of complex ones such as socket are different.

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:35:29

    You can use tbox + xmake for perfect cross-platform development. .

    http://xmake.io
    http://tboox.org

    reply
    0
  • Cancelreply