在Visual Studio 2015下使用pthread win32编译报错

版权声明:本文为博主原创文章,转载请注明源地址。 https://blog.csdn.net/10km/article/details/82982274

pthread for win32的发行版本中只提供了动态库,今天在Visual Studio 2015下编译pthread for win32(2.9.1),想编译一个静态库,就报一个struct timespec重定义的错误,如下:

cl /I. /DHAVE_PTW32_CONFIG_H /O2 /Ob2 /W3 /MD /nologo /DPTW32_BUILD_INLI
NED /DPTW32_STATIC_LIB /D__CLEANUP_C -c pthread.c
pthread.c
d:\tmp\pthreads-w32-2-9-1-release\pthreads.2\pthread.h(320): error C2011: “timespec”:“struct”类型重定义
C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\time.h(39): note: 参见“timespec”的声明
d:\tmp\pthreads-w32-2-9-1-release\pthreads.2\pthread_mutex_consistent.c: warning	 C4819: 该文件包含不能在当前代码页(936)中表示的字符。请将该文件保存为 Unicode 格式以防止数据丢失
NMAKE : fatal error U1077: “"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.EXE"”: 返回代码“0x2” Stop.
NMAKE : fatal error U1077: “"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe"”: 返回代码“0x2”Stop.

在Visual Studio 2015下只是#include <pthread.h>,编译也会报同样的错。

原因也很简单pthread for win32的最新版本是2012年出的。那时还没有Visual Studio 2015,Visual Studio 2015之前的版本中time.h中没有timespec结构定义,所以pthread.h中定义了struct timespec
到了Visual Studio 2015,在time.h中增加了timespec结构定义,于是就出错了。

解决方案1

修改pthread.h,在line 320之前加上宏定义根据MSVC版本号,判断是否要定义struct timespec
如下:

// 在line 320前增加下面三行,根据_MSC_VER 和_CRT_NO_TIME_T判断timespec是否定义
#if defined(_MSC_VER) && _MSC_VER >= 1900 && !defined(_CRT_NO_TIME_T)
#define _TIMESPEC_DEFINED
#endif
// line 320
#if !defined(HAVE_STRUCT_TIMESPEC)
#define HAVE_STRUCT_TIMESPEC
#if !defined(_TIMESPEC_DEFINED)
#define _TIMESPEC_DEFINED
struct timespec {
        time_t tv_sec;
        long tv_nsec;
};
#endif /* _TIMESPEC_DEFINED */
#endif /* HAVE_STRUCT_TIMESPEC */

如果你想自己在VS2015下重新编译pthread for win32,那么只能用这个办法。

解决方案2

如果你只是在自己的项目中引用pthread.h,并不需要重新编译pthread for win32,
那么没必要修改pthread.h,在自己的项目中#include <pthread.h>之前加上宏定义HAVE_STRUCT_TIMESPEC_TIMESPEC_DEFINED

#if defined(_MSC_VER) && _MSC_VER >= 1900 && !defined(_CRT_NO_TIME_T)
#define _TIMESPEC_DEFINED
#endif
#include <pthread.h>

这个方法的好处就是不需要修改pthread for win32的代码,在己方代码中解决问题。代码管理比较方便。

猜你喜欢

转载自blog.csdn.net/10km/article/details/82982274