Visual Studios,在 C 代码中使用预编译的 header

Visual Studios, using using a precompiled header in C code

我正在将我在 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.
 * 
 */

#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"

但是,我在执行此操作时遇到错误。 "Precompiled header file is from a previous version of the compiler, or the precompiled header is C++ and you are using it from C (or vice versa)"。这发生在 getopt.c.

现在我尝试将设置更改为 "Not using Precompiled Headers",但是当我这样做时,我在 unistd.h 第 48 行收到错误“'int8_t':重新定义;不同的基本类型” . 是否有另一个预编译的 header 我应该用于 c 代码或解决此问题的方法?谢谢!

编辑:另外,为了验证,我在每个 .h 文件的顶部都有#pragma once。

首先从您的 unistd.h 文件中删除所有这些 typedef 定义(int8_tint16_t 等)。这些已经通过包含 <stdint.h> 来定义,它在 Windows 上可用。在禁用预编译 headers.

后,这可能会让你得到修复

您可能已经发现,您不能同时将预编译的 header 与 C 和 C++ 混合使用。几种可能的解决方案:

  1. 在单独的静态库 (lib) 中构建您的 "C" 代码,并使用它自己的预编译 header(例如 "pch.h" 和 "pch.c")。或者干脆跳过这个项目的预编译 header 东西。然后你的 EXE 是用 C++ 代码构建的,并链接到你的 C 代码的 LIB。

  2. 或者只需将 getopt.c 重命名为 getopt.cpp。通过一两次快速修复,它可能会编译得很好。然后将所有 C++ 代码与预编译的 header 一起构建。