如何象使用Java那样写出C++的跨平台程序是每个程序都要考虑的问题。这里提供一个简便的方法,实现这个想法。
主要思想是把平台独立代码和平台相关代码分离。
一、平台独立代码
// main.cpp
#include "platform_related.hpp"
int main() {
handle_t n = OwnLoadLibrary("libraryName");
// 其他代码
……
}
二、平台相关代码
// platform_related.hpp
#ifdef WIN32
#include "win32_related.hpp"
#endif
#ifdef WINCE
#include "wince_related.hpp"
#endif
#ifdef UNIX
#include "unix_related.hpp"
#endif
#ifdef SOLARIS
#include "solaris_related.hpp"
#endif
#ifdef AIX
#include "aix_related.hpp"
#endif
// unix_related.hpp
int main()
{
int h = dlopen("library", RTLD_LAZY);
// 其他代码
}
// win32_related.hpp
int main() {
// todo
HMODULE h = LoadLibrary("library");
// 其他代码
}
其他细节需要注意:
使用系统标准库
(1) 文件操作 fstream fopen fclose
(2) 线程同步 pthreads
(3) 字符符操作 string