C++ 如何兼容Linux和window?
迷茫
迷茫 2017-04-17 14:33:29
0
7
1018

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(7)
小葫芦

You need to encapsulate the differences between platforms yourself

void Sleep(const unsigned int milliseconds)
{
#ifdef _WIN32
   ::Sleep(milliseconds);
#else
   usleep(milliseconds * 1000);
#endif
}
左手右手慢动作

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

左手右手慢动作

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

PHPzhong

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

Ty80

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

黄舟

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.

迷茫

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

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template