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


using std::vector;
using std::string;

struct Settings
{
    vector<string> allowable = { "-t", "--type", "-v", "--verbosity" };
};


MS 知道这个问题并且在后面版本的 VS 中修复了,所以没有什么特别需求的话还是推荐用最新的工具。

min max

另一个令人讨厌的问问题是windows.h内带有奇怪的 macro defination:

min
max
near
far

前面两个很多人遇到过,后面两个嘛,做3D开发的朋友应该是要骂人的。处理方法其实很简单


			#ifdef min
			#undef min
			#endif

			#ifdef max
			#undef max
			#endif


Math 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 // !_WIN32

strsep

#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 = '';
        *stringp = p + 1;
    }

    return start;
}


#endif // _WIN32


MultiThread 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