C++ 声明如何与自身冲突?

C++ 声明如何与自身冲突?,c++,g++,solver,C++,G++,Solver,这是我在尝试编译使用taucs(不是我的代码)的代码时遇到的错误: 沃特?这是自相矛盾的吗 在我掐住自己之后,我创建了一个测试头并输入了一个冲突的定义,以确保我在这方面是正确的: 在testit.h文件中: #include "somethingelse.h" typedef struct { int n; } foobar; typedef struct { int n; } foobar; typedef struct { int n; } foobar; testit.

这是我在尝试编译使用taucs(不是我的代码)的代码时遇到的错误:

沃特?这是自相矛盾的吗

在我掐住自己之后,我创建了一个测试头并输入了一个冲突的定义,以确保我在这方面是正确的:

在testit.h文件中:

#include "somethingelse.h"

typedef struct
{
  int n;
} foobar;
typedef struct
{
  int n;
} foobar;

typedef struct
{
  int n;
} foobar;

testit.h:9: error: conflicting declaration ‘typedef struct foobar foobar’
testit.h:4: error: ‘foobar’ has a previous declaration as ‘typedef struct foobar foobar’
在文件somethingelse.h中:

typedef struct
{
  int n;
} foobar;
果然,我得到了:

testit.h:6: error: conflicting declaration ‘typedef struct foobar foobar’
somethingelse.h:4: error: ‘foobar’ has a previous declaration as ‘typedef struct foobar foobar’
或者如果我在testit.h中有这个:

#include "somethingelse.h"

typedef struct
{
  int n;
} foobar;
typedef struct
{
  int n;
} foobar;

typedef struct
{
  int n;
} foobar;

testit.h:9: error: conflicting declaration ‘typedef struct foobar foobar’
testit.h:4: error: ‘foobar’ has a previous declaration as ‘typedef struct foobar foobar’

行号总是不同的——声明本身不能冲突。我不明白。有人见过这个吗?

可能是因为包含声明的头文件(
../taucs/src/taucs.h
)被两个单独的
#include
指令(直接或间接)包含了两次吗?

多个源文件中是否包含一个头文件?如果是这样,您需要将其包装为“包含防护装置”,如下所示:


在本例中,您给出了两个foobar声明。编译器不知道选择哪一个-因此它会使用冲突声明退出。同一事物不能声明两次。

不要重复定义。C++允许一个定义只出现一次。你能做的就是重复一个声明

typedef
始终是一个定义。因此,我首先推荐的是给<代码>结构> <代码>一个适当的名称(并且因为这是C++,TyPulf不会增加任何好处,所以只需删除TyBueF):

接下来,它应该正好在一个文件中。如果您的文件仅使用指向foobar的指针,则可以重复声明(而不是定义):


我的代码也有同样的问题,它不是类型的双重声明。PC皮特抱怨在混合C和C++代码中使用的相同的Type。我可以通过避免C和C++文件中的相同声明来修复。希望这对某人有所帮助。

不过,你应该避免前面的双下划线。这些名称是保留的,后面的双下划线也是保留的。正确的形式应该是
TAUCS\u H
。C和C++程序员不会使用宏加后缀来实现其他目的,所以这是安全的,没有进一步的修饰。我决定给它的复选标记,因为它是第一次出现的。
typedef struct
{
   int n;
} foobar;

typedef struct
{
   int n;
} foobar;

testit.h:9: error: conflicting declaration ‘typedef struct foobar foobar’
testit.h:4: error: ‘foobar’ has a previous declaration as ‘typedef struct foobar foobar’
// file1.h
struct foobar
{
    int n;
};
// file2.h

// This is just a declaration so this can appear as many times as
// you want
struct foobar;

void doit(const foobar *f);