Linux 工程向 Windows 平台迁移的一些小小 tips
Linux 工程向 Windows 平臺遷移的一些小小 tips
VS2013 C++11
Visual Studio 2013 沒有做到對 C++11 所有的支持,其中存在的一個特性就是 In-class member initializer
例如我們的代碼在某個類的構造函數中使用初始化列表,并用{}對其中一個類類型的成員初始化,這樣的寫法是符合 C++11 語法的,但是編譯無法通過。另一個例子參見 SO 的問題:
In-class member initializer fails with VS 2013
MS 知道這個問題并且在后面版本的 VS 中修復了,所以沒有什么特別需求的話還是推薦用最新的工具。
min max
另一個令人討厭的問問題是windows.h內帶有奇怪的 macro defination:
min max near far前面兩個很多人遇到過,后面兩個嘛,做3D開發的朋友應該是要罵人的。處理方法其實很簡單
#ifdef min#undef min#endif#ifdef max#undef max#endifMath Constants
#define _USE_MATH_DEFINES // for C++ #include <cmath>#define _USE_MATH_DEFINES // for C #include <math.h>gettimeofday
關于這個函數,有兩種解決方案,如果一開始就是寫跨平臺的代碼,那么不如索性使用 C++11 的時間函數,這個是真正跨平臺的(多線程也一樣)。舉例如下:
std::chrono::time_point<std::chrono::system_clock> start_time =std::chrono::system_clock::now(); // Do ... std::chrono::time_point<std::chrono::system_clock> end_time =std::chrono::system_clock::now();std::chrono::milliseconds time_diff =std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);如果需要兼容舊的 Linux 的代碼,那么不妨使用下面的這一份實現:
#ifdef _WIN32 /* FILETIME of Jan 1 1970 00:00:00. */ static const unsigned __int64 epoch = ((unsigned __int64)116444736000000000ULL);/** timezone information is stored outside the kernel so tzp isn't used anymore.** Note: this function is not for Win32 high precision timing purpose. See* elapsed_time().*/ int gettimeofday(struct timeval * tp, struct timezone * tzp) {FILETIME file_time;SYSTEMTIME system_time;ULARGE_INTEGER ularge;GetSystemTime(&system_time);SystemTimeToFileTime(&system_time, &file_time);ularge.LowPart = file_time.dwLowDateTime;ularge.HighPart = file_time.dwHighDateTime;tp->tv_sec = (long)((ularge.QuadPart - epoch) / 10000000L);tp->tv_usec = (long)(system_time.wMilliseconds * 1000);return 0; } #endif // !_WIN32strsep
#ifdef _WIN32 #include <time.h>char* strsep(char** stringp, const char* delim) {char* start = *stringp;char* p;p = (start != NULL) ? strpbrk(start, delim) : NULL;if (p == NULL){*stringp = NULL;}else{*p = '\0';*stringp = p + 1;}return start; }#endif // _WIN32MultiThread Lib
需要保證所有的模塊都是使用一樣的多線程庫,因為 Windows 下的工程是由 CMAKE 生成的,所以直接在 CMakeLists 里面設置好:
elseif(MSVC)set(CMAKE_CXX_FLAGS ".......")set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MT")轉載于:https://www.cnblogs.com/psklf/p/10320592.html
總結
以上是生活随笔為你收集整理的Linux 工程向 Windows 平台迁移的一些小小 tips的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux下安装MongoDB全程记录
- 下一篇: 构造方法,this,super关键字