user994165
user994165

Reputation: 9512

Including a typedef in two header files

I have this in ball.h:

#ifndef BALL_H_
#define BALL_H_
...
typedef void *PBALL  ;
...
#endif

in paddle.h I have:

#ifndef PADDLE_H_
#define PADDLE_H_
...
int contact_made(struct pppaddle*, PBALL);
...
#endif

I get an error in paddle.h because it doesn't know about PBALL. So if I add:

#ifndef BALL_H_
#include    "ball.h"
#endif

to paddle.h (with or without the if statement) it works in my Cygwin environment. But in Linux when I go to compile I get: "multiple definition of `newPBALL'" error on the source file that uses PBALL and also on the functions defined in ball.h. How can I get paddle.h to understand PBALL without running into these problems in Linux?

My ball.c file:

struct newball {
    int x_pos, x_dir, y_pos, y_dir, y_delay, y_count, x_delay, x_count;
    char symbol;
};

typedef struct newball *ball_struct_ptr;
struct newball the_ball;

#include "ball.h"

PBALL newPBALL() {

    the_ball.y_pos = Y_INIT;
    the_ball.x_pos = X_INIT;
    the_ball.y_count = the_ball.y_delay = Y_DELAY;
    the_ball.x_count = the_ball.x_delay = X_DELAY;
    the_ball.y_dir = 1;
    the_ball.x_dir = 1;

    the_ball.symbol = DFL_SYMBOL;       //Set the symbol of the ball

    PBALL ptr = &the_ball;
    return ptr;
}

Upvotes: 3

Views: 2310

Answers (2)

user994165
user994165

Reputation: 9512

Well instead of trying to import one header file into another (which worked in Cygwin but not Linux) or not importing the header into the other header (which worked for Linux but not Cygwin) I did this in both header files:

#ifndef TYPEDEF_PBALL_DECLARED_
#define TYPEDEF_PBALL_DECLARED_
typedef void *PBALL  ;
#endif

Now it's working in both environments. I'll leave this open for a little while in case there is a better solution than having to declare typedef twice in two header files.

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249384

I don't know what precisely is the problem, but I might be able to tell you how to figure it out.

Build your program as usual. Capture the command line of the failing compilation step. This might be something like:

gcc -c -o foo/bar.o baz.c

So baz.c presumably #includes the "bad" header files. And you get the compilation error. Now, track it down by just preprocessing your sources:

gcc -E -o foo/bar.c baz.c

-E being the option to stop after preprocessing, before actual compilation. Now try to compile the preprocessed file:

gcc -c -o foo/bar.o bar.c

You should find a similar error as before. Now look at the preprocessed source in bar.c from step 2 and you might easier find the cause. Start with just searching for the identifier that the compiler is complaining about--is it in fact declared multiple times? If so, why? Could it be in another header? Or perhaps there is a #define somewhere that is messing with your names?

Upvotes: 0

Related Questions