views:

121

answers:

2

I have successfully added a dynamic library to a program, but when I try to include the header file in a second file of the project I get errors about class redeclaration. I will add more info if this isn't enough

+5  A: 

You need to put guards into your header so it isn't included multiple times. For file 'my.h', you can add something along the lines of:

#ifndef MY_H
#define MY_H

// Header declarations here

#endif

This way, you can include the .h file multiple times but it will only be included the first time.

dj2
thx alot :D Do I only need to put the header or do I need to put the whole file or whole class
yan bellavance
All of the contents of your header file will be inside the ifdef. This includes your class definition but not your method definitions.
dj2
@dj2: why not the method definitions?
Martin York
@Martin: I guess the thinking is that you can repeat function declarations without running into problems, but you can't repeat type definitions. I think the thinking is accurate, but aconventional. It is better to have the entire body of the header inside the protective #ifdef/#endif. It is also to have the #define at the top of the file and not at the bottom.
Jonathan Leffler
Mostly because I mis-typed, heh. You should have the method signatures inside the ifdef but only your header file needs to be wrapped.I was attempting to say that stuff you'd put in your .c file doesn't need an ifdef wrap around it.
dj2
+4  A: 

An #include will replace the #include statement with the files content; having multiple #include's of the same file will therefore redefine the elements multiple times. The typical way is a safeguard like:

/* file foo .h */
#ifndef _FOO_H
#define _FOO_H

/* content */

#endif
johannes
thx ;) now I see why its put everywhere.
yan bellavance
Small reservation with this answer:IIRC "leading undercore + leading uppercase letter" names are only reserved for symbol names not macros. But for consistancy I'd say don't use the leading underscore for macros. In my shop we go for the form "Foo_h_included_". Chnaces of that clashing with anything are pretty small.
Andy J Buchanan
so on top of no leading underscore you add _included and follow the case?
yan bellavance
Yes. Though we're actually reviewing our coding standards at the moment and some people want to force these macros to uppercase to match our other macro usages. It's a good argument, but we have thousands of files already written, so consistency will probably carry the day. Hmmm.
Andy J Buchanan