How can a declaration conflict with itself?
This is the error I'm getting when trying to compile some code that uses taucs (not my code):
.../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’
wat? It is conflicting with itself?
After I pinched myself, I created a test header and put in a conflicting definition, just to make sure I was right about this:
In file testit.h:
#include "somethingelse.h"
typedef struct
{
int n;
} foobar;
In file somethingelse.h:
typedef struct
{
int n;
} foobar;
Sure enough, I get:
testit.h:6: error: conflicting declaration ‘typedef struct foobar foobar’
somethingelse.h:4: error: ‘foobar’ has a previous declaration as ‘typedef struct foobar foobar’
Or if I have this in testit.h:
typedef struct
{
int n;
} foobar;
typedef struct
{
int n;
} foobar;
testit.h:9: error: conflicting declaration ‘typedef struct foobar foobar’
开发者_StackOverflow社区testit.h:4: error: ‘foobar’ has a previous declaration as ‘typedef struct foobar foobar’
The line number is always different -- a declaration can't conflict with itself. I don't get it. Anyone ever seen this?
Is the single header included in multiple source files? If so, you need to wrap it in "include guards" like so:
#ifndef TAUCS_H
#define TAUCS_H
//Header stuff here
#endif //TAUCS_H
Could it be that your header file (.../taucs/src/taucs.h
), which contains the declaration, is (directly or indirectly) included twice by two separate #include
directives?
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’
In this example you give 2 declarations of foobar. The compiler does not know which one to choose - so it bails out with conflicting declaration. You can't declare the same thing twice.
Don't repeat the definition. C++ allows a definition to only appear one time. What you can do is repeat a declaration.
A typedef
is always a definition. So the first thing I would recommend is giving the struct
proper a name (and since this is C++, a typedef does not add any benefit so just drop the typedef):
// file1.h
struct foobar
{
int n;
};
Next, that should be in exactly one file. If you have files that only use pointers to foobar, you can repeat the declaration (just not the definition):
// file2.h
// This is just a declaration so this can appear as many times as
// you want
struct foobar;
void doit(const foobar *f);
I had the same issue linting my code and it was not double declaration of a type. PC-Lint complained about the same typedef being used in mixed C and C++ code. I could fix that by avoiding the same declaration in C and C++ files. Hope that helps someone.
精彩评论