spinning
spinning

Reputation: 119

#ifndef not working as expected

Getting a LNK2005 "already defined in GUI.obj" for a function pointer in PAL.h

//GUI.cpp
#include "PAL.h"

//PAL.h
#define PAL_INCLUDE
int (*addPAL)( int, void(*)(), void(*)() );

//main.cpp
#include "GUI.h"
#ifndef PAL_INCLUDE
#include "PAL.h"
#endif

Have I misunderstood the nature of includes and #ifndef?

Upvotes: 2

Views: 13487

Answers (4)

Cyclonecode
Cyclonecode

Reputation: 30121

You're getting the error probably because the preprocessor is processing main.cpp before GUI.cpp. Try changing the content of your PAL.h to this:

 #ifndef PAL_INCLUDED
 #define PAL_INCLUDED
 // definitions
 #endif

Reference

Include guard

Upvotes: 5

Lexi
Lexi

Reputation: 1730

Main.cpp and GUI.cpp are compiled separately from each other and then linked together. This means the preprocessor state is reset between the two compiles, and you lose the definition of PAL_INCLUDE
Header guards stop a header from being included more than once by other headers in the same compile unit, not to prevent clashes in the linker.

Try putting static in front of the method declaration - it limits the function to the current unit, thus preventing this problem. For more information, see What is a “static” function?

Upvotes: 4

Joseph Stine
Joseph Stine

Reputation: 1022

addPal is getting defined twice, once in GUI.cpp and once in main.cpp. What you want is to define it once and declare it everywhere you need to use it. I suggest putting

int (*addPAL)( int, void(*)(), void(*)() );

in one of the .cpp files (I haven't seen enough code to decide which one it belongs in), then the declaration:

extern int (*addPAL)( int, void(*)(), void(*)() );

in the header file. The extern tells the compiler that the pointer addPAL exists, but is defined elsewhere

Upvotes: 2

frarees
frarees

Reputation: 2258

I think you should use the include guard over PAL.h.

If I understand what you're trying to do, this code is much more clear (and quite common out there):

GUI.h

#ifndef _GUI_H_
#define _GUI_H_
...
#endif

GUI.cpp

#include "PAL.h"
...

PAL.h

#ifndef _PAL_H_
#define _PAL_H_

int (*addPAL)( int, void(*)(), void(*)() );

#endif

main.cpp

#include "GUI.h"
#include "PAL.h"
...

Hope it helps.

Upvotes: 3

Related Questions