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

.../taucs/src/taucs.h:554: error: conflicting declaration ‘typedef struct taucs_ccs_matrix taucs_ccs_matrix’
.../taucs/src/taucs.h:554: error: ‘taucs_ccs_matrix’ has a previous declaration as ‘typedef struct taucs_ccs_matrix taucs_ccs_matrix’

什么?这本身就是矛盾的吗?

在我捏了自己之后,我创建了一个测试标头并放入了一个相互冲突的定义,只是为了确保我对此的理解是正确的:

在文件 testit.h 中:

#include "somethingelse.h"

typedef struct
{
  int n;
} 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 中有这个:

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 指令?

其他提示

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

#ifndef TAUCS_H
#define TAUCS_H

//Header stuff here

#endif //TAUCS_H
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’

在此示例中,您给出了2个Foobar的声明。编译器不知道要选择哪一个 - 因此,它会以冲突的声明释放。您不能两次声明同一件事。

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

一种 typedef 总是一个定义。所以我建议的第一件事是给 struct 适当的名称(并且由于这是C ++,因此Typedef不会添加任何好处,因此只需删除Typedef):

// file1.h
struct foobar
{
    int n;
};

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

// file2.h

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

void doit(const foobar *f); 

我曾经有同样的问题,因为我的代码是 不是 双重声明类型。 PC-LINT抱怨混合C和C ++代码中使用的类型FEFEF。我可以通过避免C中的同样声明来解决这个问题 C ++文件。希望对某人有帮助。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top