【问题标题】:GCC strange behaviour with full path include vs search path include完整路径包含与搜索路径包含的 GCC 奇怪行为
【发布时间】:2012-06-12 18:15:33
【问题描述】:

我遇到了我试图理解的 GCC 包含行为。我提供的示例是最简单的测试代码,实际代码(以及此行为)是我用来检测代码的工具的结果。我必须使用这个工具。我只是想了解出现错误的原因。有趣的是,g++ 工作正常。示例如下:

如果我包含 <sys/types.h> 一切都编译得很好,但如果我包含 "/usr/include/sys/types.h" 则会出现错误。

这是我运行下面第一个包含完整路径的gcc 命令时出现的错误:

In file included from hello.c:7:
/usr/include/sys/types.h:195: error: redefinition of typedef ‘int8_t’
hello.c:5: error: previous declaration of ‘int8_t’ was here

编译器命令,使用 GCC 4.1.2 (CentOS 5) 导致错误:

gcc -g -I. --verbose -c -o hello.o -DLONG_INCLUDE hello.c

或者这个不会导致错误的

gcc -g -I. --verbose -c -o hello.o hello.c

代码:

/* hello2.h */

#ifdef _cplusplus
extern "C" {
#endif

int myFunc(int *a);

#ifdef _cplusplus
}
#endif



/* hello.c */
#include <stdio.h>
#include <string.h>
typedef signed char int8_t;
#ifdef LONG_INCLUDE
#include "/usr/include/sys/types.h"
#else
#include <sys/types.h>
#endif
#include "hello.h"


int myFunc(int *a)
{

  if (a == NULL)
    return -1;

  int b = *a;

  b += 20;

  if (b > 80)
    b = 80;

  return b;
}

谢谢

更新:

在通过gcc -E 查看预处理器输出后,看起来在指定完整路径时,gcc 不会将其视为系统包含路径,并且不知何故,它正在促成(导致?)错误。尝试对/usr/include/usr/include/sys 使用-isystem 选项,但无济于事。

【问题讨论】:

  • 可能不相关:宏名为__cplusplus。您缺少下划线。此外,所有这些都可以在非古代 gcc 上编译。
  • @pmr 谢谢,不幸的是,我坚持使用 GCC 和 dang 工具的版本。在这一点上,我只是想了解为什么 GCC 将其视为非系统标头。
  • 正如你所说,isystem 似乎是去这里的方式。我想知道为什么您首先需要完全限定路径。这似乎有点……坏了。
  • 该工具正在做所有这些,是的,它真的坏了。奇怪的是isystem没有帮助
  • 我在 gcc-4.5.1 上得到了相同的行为(那已经很古老了,@pmr?)。尝试设置-D__int8_t_defined,以保护int8_t 和我的&lt;sys/types.h&gt; 中的朋友类型定义。

标签: c gcc include


【解决方案1】:

在 Glibc 的 &lt;sys/types.h&gt; 中,int8_t 等的 typedef 由

#if !__GNUC_PREREQ (2, 7)

/* These types are defined by the ISO C99 header <inttypes.h>. */
# ifndef __int8_t_defined
#  define __int8_t_defined
typedef char int8_t;
typedef short int int16_t;
typedef int int32_t;
#  if __WORDSIZE == 64
typedef long int int64_t;
#  elif __GLIBC_HAVE_LONG_LONG
__extension__ typedef long long int int64_t;
#  endif
# endif

因此,解决该问题的方法是在命令行上定义保护宏,除了 -DLONG_INCLUDE 之外还传递 -D__int8_t_defined

【讨论】:

    猜你喜欢
    • 2014-05-09
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多