9

这是我在尝试编译一些使用 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’

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

4

5 回答 5

16

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

#ifndef TAUCS_H
#define TAUCS_H

//Header stuff here

#endif //TAUCS_H
于 2010-08-24T03:03:51.733 回答
7

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

于 2010-08-24T03:02:16.380 回答
1
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 的声明。编译器不知道该选择哪一个 - 所以它会以冲突的声明退出。您不能两次声明同一件事。

于 2010-08-24T05:17:29.000 回答
1

不要重复定义。C++ 允许定义只出现一次。您可以做的是重复声明。

Atypedef始终是一个定义。所以我建议的第一件事是给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); 
于 2010-08-24T05:30:41.990 回答
0

我在检查代码时遇到了同样的问题,这不是类型的双重声明。PC-Lint 抱怨在混合的 C 和 C++ 代码中使用了相同的 typedef。我可以通过避免在 CC++ 文件中使用相同的声明来解决这个问题。希望对某人有所帮助。

于 2016-05-17T14:36:39.930 回答