我正在将我在 linux 上编写的代码导入到 Visual Studio,我正在用我在 Stack Overflow 上找到的这个文件替换 unistd.h 文件:
#ifndef _UNISTD_H
#define _UNISTD_H 1
/* This is intended as a drop-in replacement for unistd.h on Windows.
* Please add functionality as neeeded.
* https://stackoverflow.com/a/826027/1202830
*/
#include <stdlib.h>
#include <io.h>
#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */
#include <process.h> /* for getpid() and the exec..() family */
#include <direct.h> /* for _getcwd() and _chdir() */
#define srandom srand
#define random rand
/* Values for the second argument to access.
These may be OR'd together. */
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
//#define X_OK 1 /* execute permission - unsupported in windows*/
#define F_OK 0 /* Test for existence. */
#define access _access
#define dup2 _dup2
#define execve _execve
#define ftruncate _chsize
#define unlink _unlink
#define fileno _fileno
#define getcwd _getcwd
#define chdir _chdir
#define isatty _isatty
#define lseek _lseek
/* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */
#ifdef _WIN64
#define ssize_t __int64
#else
#define ssize_t long
#endif
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#endif /* unistd.h */
这包括 github 上的 getopt.h 和 getopt.c 文件。我已将其包含在项目中的 main.cpp 中。在每个代码的顶部,我添加了
#include "pch.h"
但是,执行此操作时出现错误。“预编译头文件来自以前版本的编译器,或者预编译头文件是 C++ 并且您正在从 C 使用它(反之亦然)”。这发生在 getopt.c 中。
现在我已经尝试将设置更改为“不使用预编译头”,但是当我这样做时,我在 unistd.h 第 48 行收到错误“'int8_t':redefinition; different basic types”。是否还有另一个预编译头我'我应该用于 c 代码还是一种解决此问题的方法?谢谢!
编辑:另外,为了验证,我确实在每个 .h 文件的顶部有 #pragma 一次。
首先删除所有这些类型定义的定义(int8_t
,int16_t
从你的,等..)unistd.h
文件。这些已经由包括定义<stdint.h>
,它在 Windows 上可用。这可能会让您在禁用 precomp 标头后得到修复。
正如您可能已经发现的那样,您不能同时将预编译头文件与 C 和 C++ 混合使用。几种可能的解决方案:
在单独的静态库 (lib) 中构建您的“C”代码,并使用它自己的预编译头文件(例如“pch.h”和“pch.c”)。或者只是完全跳过这个项目的预编译头文件。然后你的 EXE 是用 C++ 代码构建的,并链接到你的 C 代码库。
或者干脆将您的重命名getopt.c
为getopt.cpp
. 它可能会通过一两个快速修复编译得很好。然后将所有的 C++ 代码与预编译的头文件一起构建。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句