search

Home  >  Q&A  >  body text

c++ - 当今各种框架的跨平台技术的实现原理?

查过一点资料,现今的跨平台实现方法主要有两种,一种是“一次编译,到处运行”(就是java这种),还有一种是“一次编码,到处编译”

我现在主要有疑问的是第二种。

就拿C++语言来说,其本身是跨平台的,只要我们不调用特定系统平台的api,只用标准库,其本身是可以实现跨平台的。但是如果我们要调用系统api,那就肯定无法跨平台编译了。
所以各种跨平台框架应运而生,比如QT、cocos2d-x等等。他们都是做了一个系统平台无关的层,把各个系统的api封装起来,提供接口,然后在哪个平台下就调用哪个平台的api

首先我不知道上述我的说法有没有错误的地方,若有,还请大神们指正!

现在我还有一个疑惑就是,在哪个平台下就调用哪个平台的api是如何实现的,难道这些框架自己会判断自己处在什么操作系统下吗?那不然它怎么知道该调用哪个系统的api?还是说是别的方法原理来实现跨平台的?(比如把所有操作系统的api都放在框架的源代码里面封装起来,然后创建项目的时候选择哪个平台就行?)
我看cocos2d-x有好几个文件夹,分别对应各个平台(win32、linux、ios、Android等等),但文件夹里面就是个入口文件,不可能是整个系统的api都在里面

阿神阿神2803 days ago553

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:46:21

    Your understanding is basically correct.
    As for how a program or framework determines what system or version it is under (the same system version and different APIs are also different), this is very simple. Different systems or versions have their own characteristics, which may be unique macros. Definition, specific flag bit, or directly obtained by the corresponding function.
    Of course, although the current platforms seem to be very different, they have gradually formed some standards that are commonly recognized by everyone. For example, Windows, Linux, and Unix have all followed the POSIX interface specifications, which makes most of them commonly used The interfaces are all similar, so in a cross-platform framework, most of the code can be shared, and only a small number of rarely used interfaces need to be written separately.

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:46:21

    Cross-platform libraries are packaged according to the system API libraries of each platform.
    Each operating system has specific macros, and the code calls APIs of different platforms based on different macros. You can refer to the implementation of some excellent open source libraries.
    For example, POCO's Foundation
    There are a large number of various implementations written according to different platforms.
    https://github.com/pocoproject/poco/blob/develop/Foundation/src/NamedMutex_Android.cpp
    https://github.com/pocoproject/poco/blob/develop/Foundation/src/NamedMutex_UNIX .cpp
    https://github.com/pocoproject/poco/blob/develop/Foundation/src/NamedMutex_VMS.cpp
    https://github.com/pocoproject/poco/blob/develop/Foundation/src /NamedMutex_WIN32.cpp
    https://github.com/pocoproject/poco/blob/develop/Foundation/src/NamedMutex_WIN32U.cpp
    Then include different files in NamedMutex.cpp according to different platforms

    #if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8)
    #include "NamedEvent_WIN32U.cpp"
    #elif defined(POCO_OS_FAMILY_WINDOWS)
    #include "NamedEvent_WIN32.cpp"
    #elif defined(POCO_ANDROID)
    #include "NamedEvent_Android.cpp"
    #elif defined(POCO_OS_FAMILY_UNIX)
    #include "NamedEvent_UNIX.cpp"
    #else
    #include "NamedEvent_VMS.cpp"
    #endif

    reply
    0
  • Cancelreply