Including typedefs 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

      

in paddle.h (with or without if statement) it works in my Cygwin environment. But on Linux, when I go to compile, I get: "multiple definition of the 'newPBALL' error on the source file that uses PBALL as well as the functions defined in ball.h. How can I get paddle.h to understand PBALL without facing these issues on 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;
}

      

+3


source to share


2 answers


Instead of trying to import one header file into another (which worked in Cygwin but not Linux), or import the header into another 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


It now works in both environments. I'll leave this open for a while if there is a better solution than to declare the typedef twice in two header files.

+3


source


I don't know what the problem is, but I could tell you how to figure it out.

Build your program as usual. Capture the command line of the failed compile time. It could be something like:

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

      

So baz.c supposedly # includes "bad" header files. And you get a compilation error. Now track it down by simply preprocessing your sources:



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

      

-E - Ability to stop after preprocessing before actual compilation. Now try compiling the pre-processed 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 can more easily find the cause. Start by looking for just the identifier that the compiler is complaining about - is it actually declared multiple times? If so, why? Could it be in a different title? Or maybe there is a #define somewhere that fiddles with your names?

0


source







All Articles