声明如何与自身发生冲突?

时间:2010-08-24 02:58:19

标签: c++ g++ solver

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

行号始终不同 - 声明不能与自身冲突。我不明白。有人见过这个吗?

5 个答案:

答案 0 :(得分:14)

单个标头是否包含在多个源文件中?如果是这样,你需要将它包装在“include guard”中,如下所示:

#ifndef TAUCS_H
#define TAUCS_H

//Header stuff here

#endif //TAUCS_H

答案 1 :(得分:6)

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

答案 2 :(得分: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声明。编译器不知道选择哪一个 - 因此它会因冲突的声明而失败。你不能两次宣布同一件事。

答案 3 :(得分:0)

不要重复定义。 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); 

答案 4 :(得分:0)

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

相关问题