6

如果我想为多个平台编写我的 C++ 应用程序,例如 Windows 和 Linux,那么推荐的编写平台代码的方式是什么?存在什么模式、类层次结构等来完成这项任务?我应该如何组织我的代码、头文件和源文件?

4

2 回答 2

5

I don't get your question completely, but generally you should separate your platform dependent code from platform independent one. for example you may have a folder platform and inside it a folder for each platform that supported by you, then you may have win32/mutex.hpp, linux/mutex.hpp, mac/mutex.hpp and in each of them you may add implementation of mutex for that platform. Then all you need is a single selector header that based on platform select correct file and include it. For example platform/mutex.hpp that include any of specified files in correct platform.

But beside that, take a look at boost it implement many platform dependent code in a platform independent manner, you can learn from it and you may see implementation of your platform dependent code there!!

于 2012-10-14T21:18:36.030 回答
5
  1. Stick to standards defined by C++ ISO specifications.
  2. Use PLATFORM independent libraries (like Boost and Qt and Fltk)
  3. Make sure you don't use COMPILER specific extensions, or atleast stick to 1 SINGLE compiler(recommended: G++ which is cross platform)

    Follow these first. Patterns are but means of organising code. Standard patterns allowed by a language theoretically remain the same across all platforms, so that shouldn't be a part of the problem

  4. Use #ifdef MACROS to code platform specific path to files, platform specific libraries for networking etc.

More you remain platform independent, more you will have to rely on third party toolkits.

Organization:

FOLDERS: program
         |_plaf
         |_headers
         |_source
         |_makescripts

plaf
|_win32 //contains windows specific wrapper functions in header files
|_unix  //contains unix specific wrapper functions in header files

headers: //contains platform independent headers
lib: //contains platform independent static libraries
sources: //contains .h and .cxx(or .cc or .cpp) files. ONE file per class with main function in main.cxx
于 2012-10-14T21:18:57.660 回答