Link to home
Start Free TrialLog in
Avatar of randyg
randyg

asked on

Header Files

I'm in Dialog mode. I have a main Dialog and several Dialogs that come off of the Main Dialog. I created a Header file and in the CMyProgram1Dlg (which is the Main Dialog) I used

#include "header.h"

Everything works fine.

The problem is when I want to #include the same Header file in one of the Sub Dialogs I get this error:

pddlg.obj : error LNK2005: "unsigned int  port" (?port@@3IA) already defined in Program1.obj

pddlg.obj : error LNK2005: "int __cdecl trans(unsigned int,unsigned int,int)" (?trans@@YAHIIH@Z) already defined in Program1.obj

If I don't #include the Header file I get errors that the variables are undefined.

What am I doing wrong and what do I have to do to correct it?

Thanks
Randy
ASKER CERTIFIED SOLUTION
Avatar of chensu
chensu
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Gawande
Gawande

Always put *.h code in # directive as follows

#ifndef _HEADER_FILE_NAME           // If this variable is not defined then only header file
#define _HEADER_FILE_NAME         // will get included. Header file should be loaded                                                             // only once.  So when you include this header file
// next time, the variable is already declared and hence, it will not give you any error

.



//// Header file contents

#endif // _HEADER_FILE_NAME
It seems that my commnets are destorted, please put your code in following way

#ifndef _FILE_NAME
#define _FILE_NAME

// Header file contents

#endif
Yes, you should do what Gawande suggests. However, it does not solve the problem randyg is facing.

It does solve the problem in the following example.

Header files: a.h, b.h, c.h
Source files: a.cpp

In the a.cpp,
#include "a.h"
#include "c.h"

In the a.h,
#include "b.h"
#include "c.h"

In this case, c.h is included twice.

It does not solve the problem in the following example.

Header files: a.h
Source files: a.cpp, b.cpp

In the a.h,
unsigned int port;

In the a.cpp,
#include "a.h"

In the b.cpp,
#include "a.h"

In this case, there are two global variables port with the same name.

To solve this problem,

In the a.h,
extern unsigned int port;

Add another source file c.cpp,
unsigned int port;
hi
try to save your header file in two diffrent names
then use it.
talb,

But the variables and the functions are the same. It will still cause the linking error.